Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are several things wrong with how you're going about it.</p> <ol> <li><p>You're mixing abstraction levels. The T parameter to <code>GetAnyExpression&lt;T&gt;</code> could be different to the type parameter used to instantiate <code>propertyExp.Type</code>. The T type parameter is one step closer in the abstraction stack to compile time - unless you're calling <code>GetAnyExpression&lt;T&gt;</code> via reflection, it will be determined at compile time - but the type embedded in the expression passed as <code>propertyExp</code> is determined at runtime. Your passing of the predicate as an <code>Expression</code> is also an abstraction mixup - which is the next point.</p></li> <li><p>The predicate you are passing to <code>GetAnyExpression</code> should be a delegate value, not an <code>Expression</code> of any kind, since you're trying to call <code>Enumerable.Any&lt;T&gt;</code>. If you were trying to call an expression-tree version of <code>Any</code>, then you ought to pass a <code>LambdaExpression</code> instead, which you would be quoting, and is one of the rare cases where you might be justified in passing a more specific type than Expression, which leads me to my next point.</p></li> <li><p>In general, you should pass around <code>Expression</code> values. When working with expression trees in general - and this applies across all kinds of compilers, not just LINQ and its friends - you should do so in a way that's agnostic as to the immediate composition of the node tree you're working with. You are <strong>presuming</strong> that you're calling <code>Any</code> on a <code>MemberExpression</code>, but you don't actually <strong>need to know</strong> that you're dealing with a <code>MemberExpression</code>, just an <code>Expression</code> of type some instantiation of <code>IEnumerable&lt;&gt;</code>. This is a common mistake for people not familiar with the basics of compiler ASTs. <a href="http://weblogs.asp.net/fbouma/archive/2007/10/03/developing-linq-to-llblgen-pro-day-5.aspx" rel="noreferrer">Frans Bouma</a> repeatedly made the same mistake when he first started working with expression trees - thinking in special cases. Think generally. You'll save yourself a lot of hassle in the medium and longer term.</p></li> <li><p>And here comes the meat of your problem (though the second and probably first issues would have bit you if you had gotten past it) - you need to find the appropriate generic overload of the Any method, and then instantiate it with the correct type. Reflection doesn't provide you with an easy out here; you need to iterate through and find an appropriate version.</p></li> </ol> <p>So, breaking it down: you need to find a generic method (<code>Any</code>). Here's a utility function that does that:</p> <pre><code>static MethodBase GetGenericMethod(Type type, string name, Type[] typeArgs, Type[] argTypes, BindingFlags flags) { int typeArity = typeArgs.Length; var methods = type.GetMethods() .Where(m =&gt; m.Name == name) .Where(m =&gt; m.GetGenericArguments().Length == typeArity) .Select(m =&gt; m.MakeGenericMethod(typeArgs)); return Type.DefaultBinder.SelectMethod(flags, methods.ToArray(), argTypes, null); } </code></pre> <p>However, it requires the type arguments and the correct argument types. Getting that from your <code>propertyExp</code> <code>Expression</code> isn't entirely trivial, because the <code>Expression</code> may be of a <code>List&lt;T&gt;</code> type, or some other type, but we need to find the <code>IEnumerable&lt;T&gt;</code> instantiation and get its type argument. I've encapsulated that into a couple of functions:</p> <pre><code>static bool IsIEnumerable(Type type) { return type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition() == typeof(IEnumerable&lt;&gt;); } static Type GetIEnumerableImpl(Type type) { // Get IEnumerable implementation. Either type is IEnumerable&lt;T&gt; for some T, // or it implements IEnumerable&lt;T&gt; for some T. We need to find the interface. if (IsIEnumerable(type)) return type; Type[] t = type.FindInterfaces((m, o) =&gt; IsIEnumerable(m), null); Debug.Assert(t.Length == 1); return t[0]; } </code></pre> <p>So, given any <code>Type</code>, we can now pull the <code>IEnumerable&lt;T&gt;</code> instantiation out of it - and assert if there isn't (exactly) one.</p> <p>With that work out of the way, solving the real problem isn't too difficult. I've renamed your method to CallAny, and changed the parameter types as suggested:</p> <pre><code>static Expression CallAny(Expression collection, Delegate predicate) { Type cType = GetIEnumerableImpl(collection.Type); collection = Expression.Convert(collection, cType); Type elemType = cType.GetGenericArguments()[0]; Type predType = typeof(Func&lt;,&gt;).MakeGenericType(elemType, typeof(bool)); // Enumerable.Any&lt;T&gt;(IEnumerable&lt;T&gt;, Func&lt;T,bool&gt;) MethodInfo anyMethod = (MethodInfo) GetGenericMethod(typeof(Enumerable), "Any", new[] { elemType }, new[] { cType, predType }, BindingFlags.Static); return Expression.Call( anyMethod, collection, Expression.Constant(predicate)); } </code></pre> <p>Here's a <code>Main()</code> routine which uses all the above code and verifies that it works for a trivial case:</p> <pre><code>static void Main() { // sample List&lt;string&gt; strings = new List&lt;string&gt; { "foo", "bar", "baz" }; // Trivial predicate: x =&gt; x.StartsWith("b") ParameterExpression p = Expression.Parameter(typeof(string), "item"); Delegate predicate = Expression.Lambda( Expression.Call( p, typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), Expression.Constant("b")), p).Compile(); Expression anyCall = CallAny( Expression.Constant(strings), predicate); // now test it. Func&lt;bool&gt; a = (Func&lt;bool&gt;) Expression.Lambda(anyCall).Compile(); Console.WriteLine("Found? {0}", a()); Console.ReadLine(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload