Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In the general case this should work:</p> <pre><code>public static Expression&lt;Func&lt;T, bool&gt;&gt; Build(string propertyName, string method, params object[] args) { var propertyInfo = typeof(T).GetProperty(propertyName); var e = Expression.Parameter(typeof(T), "e"); var m = Expression.MakeMemberAccess(e, propertyInfo); var mi = m.Type.GetMethod(method, args.Select(a =&gt; a.GetType()).ToArray()); var c = args.Select(a =&gt; Expression.Constant(a, a.GetType())).ToArray(); Expression call = Expression.Call(m, mi, c); Expression&lt;Func&lt;T, bool&gt;&gt; lambda = Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(call, e); return lambda; } </code></pre> <p>The idea is that you accept any number of constant arguments, and use their types to select the appropriate overload when calling <code>GetMethod</code>. After that, you create the appropriate number of constant expressions from those arguments to pass to <code>Expression.Call</code>.</p> <p>So with the above code, you could do:</p> <pre><code>var l1 = LambdaExpressionHelper&lt;MailingListMember&gt;.Build( "EmailAddress", "StartsWith", "RoRy@"); var l2 = LambdaExpressionHelper&lt;MailingListMember&gt;.Build( "EmailAddress", "StartsWith", "RoRy@", StringComparison.OrdinalIgnoreCase); </code></pre> <p>If you also need to get the value <code>StringComparison.OrdinalIgnoreCase</code> from the string <code>"StringComparison.OrdinalIgnoreCase"</code>, I would factor this out into a separate method so that the interface of <code>Build</code> can remain generic. Exactly how to do it is covered in <a href="https://stackoverflow.com/questions/3565310/getting-enum-value-via-reflection">Getting Enum value via reflection</a> (and I guess in lots of similar questions as well).</p> <p><strong>Note</strong>: I don't have convenient access to a compiler right now, so please excuse any mistakes.</p>
 

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