Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Group By into a Dictionary Object

I am trying to use LINQ to create a Dictionary<string, List<CustomObject>> from a List<CustomObject>. I can get this to work using "var", but I don't want to use anonymous types. Here is what I have

var x = (from CustomObject o in ListOfCustomObjects
      group o by o.PropertyName into t
      select t.ToList());

I have also tried using Cast<>() from the LINQ library once I have x, but I get compile problems to the effect of it being an invalid cast.

like image 513
Atari2600 Avatar asked Oct 10 '22 16:10

Atari2600


1 Answers

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());
like image 169
Yuriy Faktorovich Avatar answered Dec 08 '22 01:12

Yuriy Faktorovich