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