LINQ Group By into a Dictionary Object

LinqDictionary

Linq Problem Overview


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.

Linq Solutions


Solution 1 - Linq

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

Solution 2 - Linq

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

Solution 3 - Linq

For @atari2600, this is what the answer would look like using ToLookup in lambda syntax:

var x = listOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToLookup(customObject => customObject);

Basically, it takes the IGrouping and materializes it for you into a dictionary of lists, with the values of PropertyName as the key.

Solution 4 - Linq

This might help you if you to Get a Count of words. if you want a key and a list of items just modify the code to have the value be group.ToList()

    var s1 = "the best italian resturant enjoy the best pasta";    
    var D1Count = s1.ToLower().Split(' ').GroupBy(e => e).Select(group => new { key = group.Key, value = group.Count() }).ToDictionary(e => e.key, z => z.value);


//show the results
                    Console.WriteLine(D1Count["the"]);
                    foreach (var item in D1Count)
                    {
                        Console.WriteLine(item.Key +" "+ item.Value);
                    }

Solution 5 - Linq

The following worked for me.

var temp = ctx.Set<DbTable>()
  .GroupBy(g => new { g.id })
  .ToDictionary(d => d.Key.id);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAtari2600View Question on Stackoverflow
Solution 1 - LinqYuriy FaktorovichView Answer on Stackoverflow
Solution 2 - LinqRuudvKView Answer on Stackoverflow
Solution 3 - LinqMichael BlackburnView Answer on Stackoverflow
Solution 4 - LinqMohamed FathallahView Answer on Stackoverflow
Solution 5 - LinqLeo BarbasView Answer on Stackoverflow