【问题标题】:How to update a ConcurrentDictionary that exist in another ConcurrentDictionary?如何更新存在于另一个 ConcurrentDictionary 中的 ConcurrentDictionary?
【发布时间】:2012-09-16 13:29:01
【问题描述】:

我有一个以 Pr_Matrix 命名的 ConcurrentDictionary:

ConcurrentDictionary<int, ConcurrentDictionary<int, float>> Pr_Matrix = new ConcurrentDictionary<int, ConcurrentDictionary<int, float>>();

以下代码的目的是将data_set.Set_of_Point数据集中每对点之间的相似度值添加到这个字典中。

foreach (var point_1 in data_set.Set_of_Point)
{
   foreach (var point_2 in data_set.Set_of_Point)
   {
       int point_id_1 = point_1.Key;
       int point_id_2 = point_2.Key;
       float similarity = selected_similarity_measure(point_1.Value, point_2.Value);

       Pr_Matrix.AddOrUpdate(point_id_1, 
       new ConcurrentDictionary<int, float>() { Keys = {  point_id_2 }, Values = { similarity } }, 
       (x, y) => y.AddOrUpdate(point_id_2, similarity, (m, n) => n));
   }
}

我无法更新存在于主 ConcurrentDictionary 中的 ConcurrentDictionary。

【问题讨论】:

  • 请在帖子中包含您遇到的例外情况。

标签: c# linq concurrentdictionary


【解决方案1】:

第一个问题是AddOrUpdate 方法返回一个Float 数据类型。您必须明确返回 ConcurrentDictionary

  Pr_Matrix.AddOrUpdate(point_id_1, new ConcurrentDictionary<int, float>() { Keys = { point_id_2 }, Values = { similarity } }

                        , (x, y) => { y.AddOrUpdate(point_id_2, similarity, (m, n) => n); return y; });

第二个问题是KeysValues集合是只读的,ConcurrentDictionary不支持Collection Initializer ,所以你必须用 Dictionary 之类的东西来初始化它:

Pr_Matrix.AddOrUpdate(
    point_id_1, 
    new ConcurrentDictionary<int, float>(new Dictionary<int, float> {{point_id_2, similarity}} ), 
    (x, y) => { y.AddOrUpdate(point_id_2, similarity, (m, n) => n); return y; }
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多