Search code examples
c#expressionwhere-clausemethodinfo

How to get the correct MethodInfo for "Where" extension method


I am trying to get return the correct "Where" extension method using reflection, in order to build a custom Expression. I have tried several ways but the closest I get, throws an exception: "An unhandled exception of type 'System.Reflection.AmbiguousMatchException' occurred in mscorlib.dll"

I know this is because there are two Where methods defined in the Enumrable class - but how can I return the Where method which using only just a predicate of

 Func<T, bool>. 

What I have at the moment is:

var collectionType = typeof(TSub);
Type tIEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionType);

MethodInfo methodInfo =
        typeof(Enumerable)
        .GetMethod("Where")                
        .MakeGenericMethod(collectionType);

I have also tried (this one returns null):

MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", new[] { typeof(TSub )});

and (also returns null)

 MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", new[] { collectionType })

and (this one returns the same Ambiguous Exception)

MethodInfo methodWhere = typeof(Enumerable).GetMethod("Where", BindingFlags.Public |      BindingFlags.Static)

Could anyone help at all please?

Thanks


Solution

  • In my opinion, the current answers, including the accepted one, are far more complicated than necessary. If you have a type T that you can use at compile time, you can get the MethodInfo like so:

    Func<IEnumerable<T>, Func<T, bool>, IEnumerable<T>> whereDelegate = Enumerable.Where;
    MethodInfo whereMethodInfo = whereDelegate.Method;
    

    As an extra bonus, this is strongly typed. It will compile only if the Enumerable.Where can be resolved, as opposed to anything that looks for a string "Where": that would compile just fine if you accidentally type "Wehre" instead, but would fail at runtime.