如何在List <list <keyvaluepair <string,double>&gt;&gt;中选择keyvaluepairs列表并修改他们的价值观? C#</列表<keyvaluepair <串,双>

时间:2012-04-05 00:40:30

标签: c# linq select key-value

现在问题非常严重。现在这是我的主要清单

List<List<KeyValuePair<string, double>>> dblWordFreqByCluster = new List<List<KeyValuePair<string, double>>>();

所以我们举个例子列表

(house,40),(home,20),(monitor,40)
(home,10),(work,60),(monitor,30)
(school,70),(home,10),(word,20)

所以每一行都是List<KeyValuePair<string, double>>,并且最大的列表包含所有这些行。

我想要做的是选择每个单词的值,它们的总和,然后在整个列表中除去单词计数。因此,在此修改后,列表将成为以下

(house,40),(home,40/3),(monitor,70/2)
(home,40/3),(work,60),(monitor,70/2)
(school,70),(home,40/3),(word,20)

这意味着获取每个键的平均值并更新每个键值。

C#4.0 WPF

1 个答案:

答案 0 :(得分:7)

Linq非常容易。首先,计算每个密钥的平均值:

var averages =
    (from list in dblWordFreqByCluster
     from kvp in list
     group kvp by kvp.Key into g
     select new 
     {
         Key = g.Key,
         Avg = g.Average(kvp => kvp.Value)
     }).ToDictionary(x => x.Key, x => x.Avg);

然后更新列表。由于KeyValuePair是不可变的,因此您需要使用新项替换项:

foreach (var list in dblWordFreqByCluster)
{
    for (int i = 0; i < list.Count; i++)
    {
        string key = list[i].Key;
        list[i] = new KeyValuePair<string, double>(key, averages[key]);
    }
}