C # Expand flat list <T> to dictionary <T, ICollection <int>>

I have a List<MyClass> :

 public int MyClass { public int One { get; set; } public int Two { get; set; } } 

Now the data can (and is) look like this:

One: 1, two: 9

One: 2, two: 9

One: 1, two: 8

One: 3, Two: 7

See how "One" appears twice? I want to project this flat sequence into a grouped Dictionary<int,ICollection<int>> :

KeyValuePairOne: {Key: 1, value: {9, 8}}

KeyValuePairTwo: {Key: 2, value: {9}}

KeyValuePairThree: {Key: 3, Value: {7}}

I assume that I need to make a combination of .GroupBy and .ToDictionary ?

+6
source share
3 answers
 var list = new List<MyClass>(); var dictionary = list.GroupBy(x => x.One) .ToDictionary(x => x.Key, x => x.ToArray()); 
+2
source

This is what the ToLookup extension method is. Where ToDictionary will throw if the key appears twice, ToLookup instead does a great job of this and does what you are looking for.

+4
source

How exactly do you do it:

 Dictionary<int, List<MyClass>> result = items.GroupBy(x => x.One).ToDictionary(x => x.Key, x => x.ToList()); 
0
source

Source: https://habr.com/ru/post/915352/


All Articles