Linq to Collections Group 通过取回原始实体

发布于 2025-01-01 05:46:24 字数 476 浏览 2 评论 0原文

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

 var filteredTools = from t in tools
                               group t by new { t.ModuleName,t.Number}
                               into g
                               select new { ModuleName = g.Key, Values = g };

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

List<Tool> tools

执行分组后,我返回 3 行(从 40 行中),因此分组正在工作。行的键为 g.Key,Values 为分组条件。无论如何,有没有办法将其与原始工具联系起来。也许每个工具的密钥应该是唯一的,因此在执行分组后,我可以从工具集合中获取原始工具。

I am grouping a collection of tools using the following code:

 var filteredTools = from t in tools
                               group t by new { t.ModuleName,t.Number}
                               into g
                               select new { ModuleName = g.Key, Values = g };

tools is a simple collection defined as follows:

List<Tool> tools

After grouping is performed I get 3 rows back (from 40 rows) so grouping is working. The rows have a key of g.Key and Values are the grouping conditions. Is there anyway to relate it back to the original tools. Maybe the key should be unique to each tool so after the grouping is performed I can fetch the original tool from the tools collection.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨敛清荷 2025-01-08 05:46:24

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

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);
    }
}

说实话,您实际上并不需要在这里使用匿名类型进行选择。你可以使用:

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);
    }
}

Yes, the tools still exist within each group:

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);
    }
}

To be honest, you don't really need your anonymous type here for the select. You could use:

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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文