Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Collections Group by getting the original entity back

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.

like image 583
azamsharp Avatar asked Jan 31 '26 22:01

azamsharp


1 Answers

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);
    }
}
like image 85
Jon Skeet Avatar answered Feb 02 '26 12:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!