通过获取原始实体,Linq到Collections Group

aza*_*arp 3 c# linq-to-entities

我正在使用以下代码对工具集合进行分组:

 var filteredTools = from t in tools
                               group t by new { t.ModuleName,t.Number}
                               into g
                               select new { ModuleName = g.Key, Values = g };
Run Code Online (Sandbox Code Playgroud)

tools是一个简单的集合,定义如下:

List<Tool> tools
Run Code Online (Sandbox Code Playgroud)

执行分组后,我得到3行(从40行),因此分组工作正常.行具有g.Key的键,值是分组条件.无论如何都要将它与原始工具联系起来.也许每个工具的密钥都应该是唯一的,因此在执行分组后,我可以从工具集中获取原始工具.

Jon*_*eet 7

是的,这些工具仍然存在于每个组中:

foreach (var group in filteredTools) 
{
    // This is actually an anonymous type...
    Console.WriteLine("Module name: {0}", group.ModuleName);
    foreach (Tool tool in group.Values)
    {
        Console.WriteLine("  Tool: {0}", tool);
    }
}
Run Code Online (Sandbox Code Playgroud)

说实话,你不需要在这里选择你的匿名类型.你可以使用:

var filteredTools = tools.GroupBy(t => new { t.ModuleName,t.Number});
foreach (var group in filteredTools) 
{
    // This is actually an anonymous type...
    Console.WriteLine("Module name: {0}", group.Key);
    foreach (Tool tool in group)
    {
        Console.WriteLine("  Tool: {0}", tool);
    }
}
Run Code Online (Sandbox Code Playgroud)