Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I just created a <code>generic filter function</code> using <code>ExpressionTree</code> .. I want to <code>share</code> with you guys... </p> <p><code>Start</code></p> <pre><code>var allFiltered= Filter(AllCustomer, "Name", "Moumit"); public static List&lt;T&gt; Filter&lt;T&gt;(this List&lt;T&gt; Filterable, string PropertyName, object ParameterValue) { ConstantExpression c = Expression.Constant(ParameterValue); ParameterExpression p = Expression.Parameter(typeof(T), "xx"); MemberExpression m = Expression.PropertyOrField(p, PropertyName); var Lambda = Expression.Lambda&lt;Func&lt;T, Boolean&gt;&gt;(Expression.Equal(c, m), new[] { p }); Func&lt;T, Boolean&gt; func = Lambda.Compile(); return Filterable.Where(func).ToList(); } </code></pre> <p><code>One More</code></p> <pre><code>string singlePropertyName=GetPropertyName((Property.Customer p) =&gt; p.Name); public static string GetPropertyName&lt;T, U&gt;(Expression&lt;Func&lt;T, U&gt;&gt; expression) { MemberExpression body = expression.Body as MemberExpression; // if expression is not a member expression if (body == null) { UnaryExpression ubody = (UnaryExpression)expression.Body; body = ubody.Operand as MemberExpression; } return string.Join(".", body.ToString().Split('.').Skip(1)); } </code></pre> <p><code>Make it more expandable</code></p> <pre><code>string multiCommaSeparatedPropertyNames=GetMultiplePropertyName&lt;Property.Customer&gt;(c =&gt; c.CustomerId, c =&gt; c.AuthorizationStatus) public static string GetMultiplePropertyName&lt;T&gt;(params Expression&lt;Func&lt;T, object&gt;&gt;[] expressions) { string[] propertyNames = new string[expressions.Count()]; for (int i = 0; i &lt; propertyNames.Length; i++) { propertyNames[i] = GetPropertyName(expressions[i]); } return propertyNames.Join(); } </code></pre> <p>....... I know it also can be done using <code>Reflection</code> ... but this one is tremendous fast or i can say equivalent to <code>Lambda</code> after first compilation ... The very first iteration is just an average 10 millisecond slow... So this is <code>Expression Tree</code> magic. Simple and fantastic....I think ...!!!!!!!!</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