Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Grouping" dictionary by value

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?

like image 786
user1260827 Avatar asked Nov 16 '12 04:11

user1260827


People also ask

How do you organize a dictionary by value?

First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary. Note: Sorting does not allow you to re-order the dictionary in-place.

How do you group dictionary using keys?

Method : Using sorted() + items() + defaultdict() The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().


1 Answers

You can use GroupBy.

Dictionary<int,List<int>> groups = 
             prices.GroupBy(x => x.Value)
                   .ToDictionary(x => x.Key, x => x.Select(i => i.Key).ToList());
like image 80
Asif Mushtaq Avatar answered Oct 06 '22 00:10

Asif Mushtaq