Accepted answer

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(
            typeof( Queryable ), "GroupBy",
            new Type[] { source.ElementType, keyLambda.Body.Type },
            source.Expression, Expression.Quote( keyLambda ) ) );


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();


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.

Related Query