Follow @endyourif rss Facebook LinkedIn

LINQ Group By into Dictionary Object 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

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP

Related Posts