C# 在带有分组的列表上创建字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/938040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:46:22  来源:igfitidea点击:

Create a dictionary on a list with grouping

c#.netlinq.net-3.5

提问by Andreas Niedermair

I have the following object in a list:

我在列表中有以下对象:

public class DemoClass
{
    public int GroupKey { get; set; }
    public string DemoString { get; set; }
    public object SomeOtherProperty { get; set; }
}

Now, I want to create following dictionary out of it:

现在,我想从中创建以下字典:

Dictionary<int, List<DemoClass>>

I want to group the List<DemoClass>by the property GroupKey, but I don't understand how this is done and some help.

我想List<DemoClass>按属性分组GroupKey,但我不明白这是如何完成的以及一些帮助。

After thinking a bit, I achieved the needed behaviour with:

经过一番思考,我通过以下方式实现了所需的行为:

var groupedDemoClasses = from demoClass in mySepcialVariableWhichIsAListOfDemoClass
                            group demoClass by demoClass.GroupKey
                            into groupedDemoClass
                            select groupedDemoClass;
var neededDictionary = groupedDemoClass.ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());

but, is there a way to make this into a single statement?

但是,有没有办法把它变成一个单一的声明?

采纳答案by Prashant Cholachagudda

var groupedDemoClasses = (from demoClass in mySepcialVariableWhichIsAListOfDemoClass
                          group demoClass by demoClass.GroupKey
                          into groupedDemoClass
                          select groupedDemoClass).ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());

This one will work !!!

这个会奏效!!!

回答by mqp

You already made it a one-liner. Just put the ToDictionaryat the end of your first line. If you want it to be shorter, use the functional composition syntax instead of the query syntax.

你已经把它做成了单线。只需将 放在ToDictionary第一行的末尾。如果您希望它更短,请使用功能组合语法而不是查询语法。

回答by Jon Skeet

Just to make mquander's suggestionconcrete:

只是为了使mquander 的建议具体化:

var groupedDemoClasses = mySpecialVariableWhichIsAListOfDemoClass
                             .GroupBy(x => x.GroupKey)
                             .ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());

You'd make it shorter if you used shorter variable names too, of course :)

当然,如果您也使用较短的变量名称,则会使其更短:)

However, might I suggest that a Lookupmight be more appropriate? A Lookup is basically a dictionary from a key to an IEnumerable<T>- unless you really needthe values as a list, it makes the code even shorter (and more efficient) with the ToLookupcall:

但是,我可以建议Lookup可能更合适吗?查找基本上是从键到键的字典IEnumerable<T>- 除非您确实需要将值作为列表,否则它可以通过ToLookup调用使代码更短(更高效):

var groupedDemoClasses = mySpecialVariableWhichIsAListOfDemoClass
                             .ToLookup(x => x.GroupKey);

回答by Mark

I'm going slightlyoff topic here, but I got to this thread becausde I was looking for a way to create a dictionary of a dictionary in Linq, and the conversation here lead me to the answer...

我在这里有点偏离主题,但是我进入了这个线程,因为我正在寻找一种在 Linq 中创建字典字典的方法,这里的对话让我找到了答案......

You canuse linq to create multi-level dictionaries, which is useful for scenarios where you've got more than 1 key or dimension that you want to search by. The trick is to create a grouping and then convert it to a dictionary, as follows:

可以使用 linq 创建多级词典,这对于您想要搜索的键或维度超过 1 个的场景非常有用。诀窍是创建一个分组,然后将其转换为字典,如下所示:

  Dim qry = (From acs In ActualSales _
             Group By acs.ProductID Into Group _
             Select ProductID, Months = Group.ToDictionary(Function(c) c.Period) _
            ).ToDictionary(Function(c) c.ProductID)

The resulting query can be used as follows:

结果查询可以按如下方式使用:

 If qry.ContainsKey(_ProductID) Then
      With qry(_ProductID)
          If .Months.ContainsKey(_Period) Then
             ...
          End If
      End With
 End If

Hope this is helpful to anyone else who needs this sort of query.

希望这对需要此类查询的其他人有所帮助。