1

How does one use Type.GetMethod() to get a method with lambda parameters? I'm trying to get the Queryable.Any method for a parameter of something like Func, using this:

typeof(Queryable).GetMethod("Any", new Type[]{typeof(Func<ObjType, bool>)})

but it keeps returning null.

Bondolin
  • 2,793
  • 7
  • 34
  • 62
  • Your problem should be related to the Any method being an extension method. – Sign Dec 11 '12 at 13:57
  • Check http://stackoverflow.com/questions/2314329/get-method-name-using-lambda-expression and http://stackoverflow.com/questions/273941/get-method-name-and-type-using-lambda-expression – Kamran Shahid Dec 11 '12 at 13:58
  • possible duplicate of [get methodinfo from a method reference C#](http://stackoverflow.com/questions/9382216/get-methodinfo-from-a-method-reference-c-sharp) – nawfal Apr 27 '13 at 14:35

1 Answers1

6

There are four things wrong:

  • There's no such thing as a "lambda parameter". Lambda expressions are often used to provide arguments to methods, but they're converted into delegates or expression trees
  • You've missed off the first parameter of Queryable.Any - the IQueryable<T>
  • You're using Func<ObjType, bool> which is a delegate type, instead of Expression<Func<ObjType, bool>> which is an expression tree type
  • You can't get at generic methods in quite that way, unfortunately.

You want:

var generic = typeof(Queryable).GetMethods()
                               .Where(m => m.Name == "Any")
                               .Where(m => m.GetParameters().Length == 2)
                               .Single();
var constructed = generic.MakeGenericMethod(typeof(ObjType));

That should get you the relevant Any method. It's not clear what you're then going to do with it.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you, that does get it. And yes, sorry, it wasn't quite the best worded question. I'm trying to put together an Expression for a dynamic Any query. Found out how to here - http://stackoverflow.com/questions/326321/how-do-i-create-this-expression-tree-in-c#326496 Thanks for the help! – Bondolin Dec 13 '12 at 19:05