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?
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.
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().
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With