I want to create a dynamic GroupBy implementation that ignores case. I am using Expression.Call
, which allows me to pass Expressions as arguments.
There are several answers on how to create a custom comparer, but this question is about how to pass a comparer dynamically.
Here is the complete method:
public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values)
{
if (source == null) throw new ArgumentNullException("source");
if (keySelector == null) throw new ArgumentNullException("keySelector");
if (elementSelector == null) throw new ArgumentNullException("elementSelector");
LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, false, values);
LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, false, values);
return source.Provider.CreateQuery(
Expression.Call(
typeof(Queryable),
"GroupBy",
new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
source.Expression,
Expression.Quote(keyLambda),
Expression.Quote(elementLambda)
)
);
}
The call to Queryable.GroupBy
is created by:
Expression.Call(typeof(Queryable), "GroupBy",
new Type[] { source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type },
source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda))
Queryable.GroupBy
allows to pass a custom IEqualityComparer
. How can I do this? Expression.Call
only allows me to pass arguments of type Expression
.
Is there any other way I can group with case ignored, by e.g. dynamically overriding GetHashCode()
of the keys?