How to select list of keyvaluepairs in List>> and modify their values ? C#

Go To StackoverFlow.com

2

Now the question is pretty hard. Now this is my main list

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

So lets give example list

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

So each line is a List<KeyValuePair<string, double>> and there is the biggest list which contains all of these lines.

What i want to do is select each word values, sum of them and then divide the word count in this whole list. So after this modification lists would become the following

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

Which means getting each keys average value and updating each keys value.

C# 4.0 WPF

2012-04-05 00:40
by MonsterMMORPG
"What i want to do is select each word values, sum of them and then divide the word count in this whole list." I'm afraid I'm not sure what you mean by that, can you rephrase - cost 2012-04-05 00:49


7

It's quite easy with Linq. First, compute the average for each key:

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);

Then update the lists. Since KeyValuePair is immutable, you need to replace the items with new ones:

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]);
    }
}
2012-04-05 00:49
by Thomas Levesque
Thanks going to try now : - MonsterMMORPG 2012-04-05 00:50
Just tried it, the results seem correct ; - Thomas Levesque 2012-04-05 00:53
Yes working nice. Wouldn't there be to modify values of the keyvaluepairs by their keys with linq ? I mean instead of the foreach loop at second part another linq which will modify the main list ? I mean it will select each of the keyvaluepairs and get that keyvaluepair new value from the dictionary and update it. That would be awesome if possible - MonsterMMORPG 2012-04-05 00:58
@MonsterMMORPG: Read the answer provided: Since KeyValuePair is immutable, you need to replace the items with new ones - This should be clear - BrokenGlass 2012-04-05 01:01
Yes i got it now :) Solution works perfect. Thanks @Thomas Levesqu - MonsterMMORPG 2012-04-05 01:11
@MonsterMMORPG, Linq doesn't provide a way to modify the data, only to query it - Thomas Levesque 2012-04-05 07:28
Ads