0

我试图找到一种优雅的方式来更新 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 来提高这项任务效率的建议。

4

3 回答 3

2

如果它真的只是即将到来的更新,你可以使用另一个ForEach

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

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

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

请注意,上面缺少检查项目是否实际包含在并发字典中 - 如果不能保证(它不是更新),您将不得不添加此检查。

于 2012-06-19T21:33:25.357 回答
1

刚刚尝试在 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
    }
于 2018-10-25T05:00:22.713 回答
0

Linq 用于查询,而不是更新。如果您能够创建一个新字典,则可以使用 Linq 的ToDictionary()方法,但是由于您必须调用一个方法来添加您或多或少地被降级为foreach循环。

此外,Linq 不会让任何事情变得更高效,它只会让代码看起来更自然。

于 2012-06-19T21:29:21.683 回答