I have a first draft for an extension method on IQueryable with an override for GroupBy which should group by a named property.
Before you ask, I’m not using the Dynamic Expression API aka Dynamic Linq because I couldn’t figure out how to access a count for each group with that. The GroupBy method in that library returns a non-generic IQueryable, rather than an IQueryable<IGrouping<>> that I need for my counts. If there is a way to get at the counts through that library, I’ll be happy to accept an answer showing me how. Perhaps some sort of syntax that I couldn’t find the documentation for in the string elementSelector parameter?
The code:
public static IQueryable<IGrouping<object, T>> GroupBy<T>(this IQueryable<T> source, string propertyName)
{
ParameterExpression param = Expression.Parameter(typeof(T), String.Empty);
MemberExpression property = Expression.PropertyOrField(param, propertyName);
LambdaExpression group = Expression.Lambda(property, param);
MethodCallExpression call = Expression.Call(
typeof(Queryable),
"GroupBy",
new[] { typeof(T), property.Type },
source.Expression,
Expression.Quote(group));
return source.Provider.CreateQuery<IGrouping<object, T>>(call);
}
I consume it like this:
public IEnumerable<Category> GetCategories(IQueryable<T> entities, string property)
{
var haba = entities.GroupBy(property);
var categories = haba.Select(group => new Category(group.Key.ToString(), group.Count()));
return categories.ToArray();
}
And it workes fine as long as my property is of type string. However, if I attempt to use it on an int or bool property I get something like the following error on the call to CreateQuery:
Argument expression has type
System.Linq.IQueryable1[System.Linq.IGrouping2[System.Int32,DerivedEntity1]]
when type
System.Collections.Generic.IEnumerable1[System.Linq.IGrouping2[System.Object,DerivedEntity1]]
was expected. Parameter name: expression
I notice that it’s expecting an IEnumerable generic rather than an IQueryable, which is strange. But a pretty good tip. You can’t cast IEnumerable to an IQueryable without doing an AsQueryable(). The question then is, why is it giving me an IEnumerable instead of an IQueryable? An why isn’t it failing in the same way when I pass in a propertyName for a string property?
I should mention that my IQueryable‘s are instances of NhQueryable, from NHibernate, that is.
I think boxing from value types is missing from your code: