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.
Get the Dynamic LINQ code and use the extension from it that allows you to specify the keySelector with a string.
You might also want to consider adding your own extension if you want to get back the entire object grouped by the key.