LINQ从另一个更新一个列表 [英] LINQ Update one list from another
问题描述
我正在尝试找到一种优雅的方法来更新ConcurrentDictionary中的值.我在下面创建了一个我要实现的目标的快速示例:
I'm trying to find an elegant way of updating values in a ConcurrentDictionary. I've created a quick example of what I'm trying to achieve below:
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&的dataLookup ConcurrentDictionary中设置ValueProperty.分别为5至111、222和333.我可以将newDataReceived对象更改为我想要的任何对象,但是我对dataLookup作为ConcurrentDictionary感到很困惑.
So in the above example I want to set the ValueProperty in the dataLookup ConcurrentDictionary with the Id of 1, 3 & 5 to 111, 222 and 333 respectively. I can change the newDataReceived object into anything I want but I'm pretty much stuck with the dataLookup as a ConcurrentDictionary.
目前,我正在遍历列表,但是正在寻找有关使用LINQ来提高此任务效率的一些建议.
At the moment I'm iterating through the list but I'm looking for some suggestions on using LINQ to make this task more efficient.
推荐答案
如果确实是即将到来的更新,则可以使用另一个ForEach
:
If it's truly just updates that are coming in, you could just use another ForEach
:
newDataReceived.ForEach(x => dataLookup[x.Id].ValueProperty = x.ValueProperty);
我个人只是用一个简单的foreach循环来表达这一点:
Personally I would just express this with a simple foreach loop though:
foreach(var update in newDataReceived)
dataLookup[update.Id].ValueProperty = update.ValueProperty;
请注意,上述方法缺少对并发字典中是否确实包含该项的检查-如果不能保证(不是更新),则必须添加此检查.
Note that above is missing a check whether the item is actually contained in the concurrent dictionary - if that is not guaranteed (it's not an update) you would have to add this check.
这篇关于LINQ从另一个更新一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!