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?
var foo = enumerableType.GetMethods(BindingFlags.Static | BindingFlags.Public)
.First(m => m.Name == "Any" && m.GetParameters().Count() == 2);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With