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

后端 未结 2 869
一生所求
一生所求 2020-12-18 11:48

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

2条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 12:10

    All you need is to construct a Func at run-time:

    var arg = Expression.Parameter(typeof(Item), "item");
    var body = Expression.Property(arg, "D");
    var lambda = Expression.Lambda>(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.

提交回复
热议问题