如何更新另一个ConcurrentDictionary中存在的ConcurrentDictionary?

时间:2012-09-16 13:29:01

标签: c# linq concurrentdictionary

我有一个以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中存在的ConcurrentDictionarys。

1 个答案:

答案 0 :(得分: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; });

并且第二个问题是 Keys Values 集合是只读的, ConcurrentDictionary 不支持 Collection Initializer < / em>,所以你必须用 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; }
);