LINQ Group By into a Dictionary Object

前端 未结 4 379
野的像风
野的像风 2021-01-30 02:07

I am trying to use LINQ to create a Dictionary> from a List. I can get this to work using \"

相关标签:
4条回答
  • 2021-01-30 02:23

    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().

    0 讨论(0)
  • 2021-01-30 02:31

    The following worked for me.

    var temp = ctx.Set<DbTable>()
      .GroupBy(g => new { g.id })
      .ToDictionary(d => d.Key.id);
    
    0 讨论(0)
  • 2021-01-30 02:32

    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.

    0 讨论(0)
  • 2021-01-30 02:41
    Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
        .GroupBy(o => o.PropertyName)
        .ToDictionary(g => g.Key, g => g.ToList());
    
    0 讨论(0)
提交回复
热议问题