我试图找到一种优雅的方式来更新 ConcurrentDictionary 中的值。我在下面创建了一个我想要实现的快速示例:
ConcurrentDictionary<int, MyDataClass> dataLookup = new ConcurrentDictionary<int, MyDataClass>();
// Initialise the example dataLookup with some dummy data
new List<MyDataClass>
{
new MyDataClass { Id = 1, ValueProperty = 0 },
new MyDataClass { Id = 2, ValueProperty = 0 },
new MyDataClass { Id = 3, ValueProperty = 0 },
new MyDataClass { Id = 4, ValueProperty = 0 },
new MyDataClass { Id = 5, ValueProperty = 0 }
}.ForEach(myClass => dataLookup.TryAdd (myClass.Id, myClass));
// incoming results that need to be fed into the above dataLookup
List<MyDataClass> newDataReceived = new List<MyDataClass>
{
new MyDataClass { Id = 1, ValueProperty = 111 },
new MyDataClass { Id = 3, ValueProperty = 222 },
new MyDataClass { Id = 5, ValueProperty = 333 }
};
因此,在上面的示例中,我想将 ID 为 1、3 和 5 的 dataLookup ConcurrentDictionary 中的 ValueProperty 分别设置为 111、222 和 333。我可以将 newDataReceived 对象更改为我想要的任何对象,但我几乎将 dataLookup 作为 ConcurrentDictionary 卡住了。
目前我正在遍历列表,但我正在寻找一些关于使用 LINQ 来提高这项任务效率的建议。