Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
317 views
Welcome To Ask or Share your Answers For Others

1 Answer

All you need is to construct a Func<Item, TKey> at run-time:

var arg = Expression.Parameter(typeof(Item), "item");
var body = Expression.Property(arg, "D");
var lambda = Expression.Lambda<Func<Item, DateTime>>(body, arg);
var keySelector = lambda.Compile();

Usage:

var result = source.GroupBy(keySelector);

It gets slightly (but not much) more difficult if you don't know the type of the property at compile-time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...