Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MethodInfo for LINQ's Any() method?

I'm trying to build an Expression that makes a call to LINQ's Any() method, and I can't seem to find the right arguments to pass to Type.GetMethod().

From the docs, it looks like Any() is implemented as a member of the Enumerable class, and that seems to work, because this shows to methods named "Any":

var enumerableType = typeof (Enumerable);
var foo = enumerableType.GetMethods().Where(m => m.Name == "Any").ToList();

And when I as for the method named "Any", I get an AmbiguousMatchException.

There are two Any() methods, in Enumerable, one takes one parameter an IEnumerable, and the other takes an IEnumerable and a Func. I want the second, and theoretically, all I need to do is to pass an array containing the two types:

var bar = enumerableType.GetMethod("Any", new[] { typeof(IEnumerable<>), typeof(Func<,>) });

But this is always returning null.

What am I doing wrong?

like image 836
Jeff Dege Avatar asked Aug 05 '14 19:08

Jeff Dege


2 Answers

var foo = enumerableType.GetMethods(BindingFlags.Static | BindingFlags.Public)
            .First(m => m.Name == "Any" && m.GetParameters().Count() == 2);
like image 180
EZI Avatar answered Nov 15 '22 04:11

EZI


If you want to specifically ensure that you're matching the overload that takes IEnumerable<> and Func<,> parameters, you can use the following (adapted from this answer):

var enumerableType = typeof(Enumerable);
var bar =
(
    from m in enumerableType.GetMethods(BindingFlags.Static | BindingFlags.Public)
    where m.Name == "Any"
    let p = m.GetParameters()
    where p.Length == 2
        && p[0].ParameterType.IsGenericType
        && p[0].ParameterType.GetGenericTypeDefinition() == typeof(IEnumerable<>)
        && p[1].ParameterType.IsGenericType
        && p[1].ParameterType.GetGenericTypeDefinition() == typeof(Func<,>)
    select m
).SingleOrDefault();
like image 5
Douglas Avatar answered Nov 15 '22 05:11

Douglas