Linq GroupBy - how to specify the grouping key at runtime?

Posted by toasteroven on Stack Overflow See other posts from Stack Overflow or by toasteroven
Published on 2010-05-26T16:00:23Z Indexed on 2010/05/26 16:11 UTC
Read the original article Hit count: 180

Filed under:
|
|

is there a good way to do a Linq GroupBy where the grouping key is determined at runtime? e.g. I want the grouping key to be built from a user-selected list of fields - can you do this? I know I can do it easily if I convert everything to a table of strings, but I was wondering if there was an elegant or clever way to accomplish this otherwise.

class Item
{
    public int A, B;
    public DateTime D;
    public double X, Y, Z;
}

I have a List<Item> called data. I want to do things like retrieve the sum of X grouped by A, or the sums of X, Y, and Z, grouped by A and B. but what fields go into the grouping should be able to be specified at runtime in some way.

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ