"Grouping" dictionary by value

user1260827 picture user1260827 · Nov 16, 2012 · Viewed 21.8k times · Source

I have a dictionary: Dictionary<int,int>. I want to get new dictionary where keys of original dictionary represent as List<int>. This is what I mean:

var prices = new Dictionary<int,int>();

The prices contain the following data:

1   100
2   200
3   100
4   300

I want to get the IList<Dictionary<int,List<int>>>:

int      List<int>
100      1,3
200      2
300      4

How can I do this?

Answer

Habib picture Habib · Nov 16, 2012
var prices = new Dictionary<int, int>();
prices.Add(1, 100);
prices.Add(2, 200);
prices.Add(3, 100);
prices.Add(4, 300);

Dictionary<int,List<int>> test  = 
                   prices.GroupBy(r=> r.Value)
                  .ToDictionary(t=> t.Key, t=> t.Select(r=> r.Key).ToList());