Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Expand Flat List<T> to Dictionary<T,ICollection<int>>

I've got a List<MyClass>:

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

Now, the data can (and does) 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'm guessing i need to do a combination of .GroupBy and .ToDictionary?

like image 549
RPM1984 Avatar asked May 10 '12 04:05

RPM1984


1 Answers

This is what ToLookup extension method is for. Where ToDictionary will throw if the key shows up twice, ToLookup instead is fine with it and does what you're looking for.

like image 50
James Manning Avatar answered Oct 23 '22 03:10

James Manning