LINQ Group By into Dictionary Object
Published on May 28, 2022
So many times to have a list of objects that I want to group - as an example - by a customer ID. The end result that I would like would be a: Dictionary<long, List>Let's begin by looking at an example of performing the group by:
var objects = myCustomObjects.GroupBy(c => c.CustomerId).ToList();
If I leave this code without converting to a dictionary the variable is of type: List<IGrouping<string, MyCustomObject>>
This is close to what I want but now let's complete the code to convert it into a dictionary:
var objects = myCustomObjects.GroupBy(c => c.CustomerId).ToDictionary(c => c.Key, c => c.ToList());
The resulting variable type is now: Dictionary<long, List<MyCustomObject>>
Tags: dictionary | linq | ASP.NET MVC and Web API Tutorial