繁体   English   中英

LINQ从另一个更新一个列表

[英]LINQ Update one list from another

我正在尝试寻找一种优雅的方法来更新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 }
};

因此,在上述示例中,我想在dataLookup ConcurrentDictionary中将ID分别为1、3和5的值属性设置为111、222和333。 我可以将newDataReceived对象更改为我想要的任何对象,但是我对dataLookup作为ConcurrentDictionary几乎一无所知。

目前,我正在遍历列表,但是正在寻找有关使用LINQ来提高此任务效率的一些建议。

如果确实是即将到来的更新 ,则可以使用另一个ForEach

newDataReceived.ForEach(x => dataLookup[x.Id].ValueProperty = x.ValueProperty);

我个人只是用一个简单的foreach循环来表达这一点:

foreach(var update in newDataReceived)
    dataLookup[update.Id].ValueProperty = update.ValueProperty;

请注意,上面没有检查该项是否确实包含在并发字典中-如果不能保证(不是更新),则必须添加此检查。

刚刚尝试在Join()中进行更新,并感到惊讶。 您显然必须实现自己的IEqualityComparer,以便仅比较所需的成员,例如ID,密钥或类似成员。

    private static void SaveProcessedFile(IEnumerable<HashedRow> processedRows, IEnumerable<HashedRow> justProcessedRows)
    {
        var comparer = new HashedRowEqualityComparerOrderLine();
        var updated = justProcessedRows.Join(processedRows, n => n, o => o, (n, o) => { o = n; return n; }, comparer); // n - new, o - old
        var inserted = justProcessedRows.Except(updated, comparer);
        // To do something
    }

Linq用于查询,而不用于更新。 如果您能够创建新字典,则可以使用Linq的ToDictionary()方法,但是由于必须调用添加方法,因此ToDictionary() foreach循环。

而且,Linq不会使任何事情更有效率 ,它只会使代码看起来更自然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM