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

后端 未结 2 868
一生所求
一生所求 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:04

    Get the Dynamic LINQ code and use the extension from it that allows you to specify the keySelector with a string.

    var query = db.Foo.GroupBy( "{0}", "GroupedProperty", groupKey );
    

    You might also want to consider adding your own extension if you want to get back the entire object grouped by the key.

    public static IQueryable GroupByComplete( this IQueryable source, string keySelector, params object[] values )
    {
        if (source == null) throw new ArgumentNullException( "source" );
        if (keySelector == null) throw new ArgumentNullException( "keySelector" );
        LambdaExpression keyLambda = DynamicExpression.ParseLambda( source.ElementType, null, keySelector, values );
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof( Queryable ), "GroupBy",
                new Type[] { source.ElementType, keyLambda.Body.Type },
                source.Expression, Expression.Quote( keyLambda ) ) );
    }
    
    0 讨论(0)
  • 2020-12-18 12:10

    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.

    0 讨论(0)
提交回复
热议问题