I appreciate that similar questions have been asked before, but I am struggling to invoke the Linq Where method in the following code. I am looking to use reflection to dynamically call this method and also dynamically build the delegate (or lambda) used in the Where clause. This is a short code sample that, once working, will help to form part of an interpreted DSL that I am building. Cheers.
public static void CallWhereMethod()
{
List<MyObject> myObjects = new List<MyObject>(){new MyObject{Name="Jon Simpson"}};
System.Delegate NameEquals = BuildEqFuncFor<MyObject>("Name", "Jon Simpson");
object[] atts = new object[1] ;
atts[0] = NameEquals;
var ret = typeof(List<MyObject>).InvokeMember("Where", BindingFlags.InvokeMethod, null, InstanceList,atts);
}
public static Func<T, bool> BuildEqFuncFor<T>(string prop, object val)
{
return t => t.GetType().InvokeMember(prop,BindingFlags.GetProperty,
null,t,null) == val;
}
As others said, extensions methods are compiler magic, you can alway use VS right click, go to definition to find the real type that implements the static method.
From there, it gets fairly hairy.
Where
is overloaded, so you need to find the actual definition that matches the signature you want.GetMethod
has some limitations with generic types so you have to find the actual one using a search.Once you find the method, you must make the
MethodInfo
specific using theMakeGenericMethod
call.Here is a full working sample:
Extension methods are really just static methods underwater. An extension method call like foo.Frob(arguments) is really just SomeClass.Frob(foo, arguments). In the case of the Where method, you're looking for System.Linq.Enumerable.Where. So get the typeof Enumerable and invoke Where on that.
Your code sample is a little confusing... unless MyObject is an enumerable.
Using reflection you'll have to invoke Where on System.Linq.Enumerable, passing in the enumerable you want to preform Where on.
I'm a bit off and late but this could help you if you need to call Linq extensions of a IEnumerable wich type is unkown.
IEnumerable<dynamic> test = obj as IEnumerable<dynamic>;
then maybe test obj if not null and
int count = test.Count()
for me that worked very well.
Extention methods are a c# compiler trick, and they don't exist in the type concerned. They (these particular ones) exist in static classes within the System.Linq name spaces. I'd suggest reflecting this in reflector and then invoking reflection on these types.