Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>After a wide research and a lot of study of Expressions I could write a solution myself. It certainly can be improved, but exactly fits my requirements. Hopefully it can help someone else.</p> <pre><code>//Return all items from a IEnumerable(target) that has at least one matching Property(propertyName) //with its value contained in a IEnumerable(possibleValues) static IEnumerable GetFilteredList(IEnumerable target, string propertyName, IEnumerable searchValues) { //Get target's T var targetType = target.GetType().GetGenericArguments().FirstOrDefault(); if (targetType == null) throw new ArgumentException("Should be IEnumerable&lt;T&gt;", "target"); //Get searchValues's T var searchValuesType = searchValues.GetType().GetGenericArguments().FirstOrDefault(); if (searchValuesType == null) throw new ArgumentException("Should be IEnumerable&lt;T&gt;", "searchValues"); //Create a p parameter with the type T of the items in the -&gt; target IEnumerable&lt;T&gt; var containsLambdaParameter = Expression.Parameter(targetType, "p"); //Create a property accessor using the property name -&gt; p.#propertyName# var property = Expression.Property(containsLambdaParameter, targetType, propertyName); //Create a constant with the -&gt; IEnumerable&lt;T&gt; searchValues var searchValuesAsConstant = Expression.Constant(searchValues, searchValues.GetType()); //Create a method call -&gt; searchValues.Contains(p.Id) var containsBody = Expression.Call(typeof(Enumerable), "Contains", new[] { searchValuesType }, searchValuesAsConstant, property); //Create a lambda expression with the parameter p -&gt; p =&gt; searchValues.Contains(p.Id) var containsLambda = Expression.Lambda(containsBody, containsLambdaParameter); //Create a constant with the -&gt; IEnumerable&lt;T&gt; target var targetAsConstant = Expression.Constant(target, target.GetType()); //Where(p =&gt; searchValues.Contains(p.Id)) var whereBody = Expression.Call(typeof(Enumerable), "Where", new[] { targetType }, targetAsConstant, containsLambda); //target.Where(p =&gt; searchValues.Contains(p.Id)) var whereLambda = Expression.Lambda&lt;Func&lt;IEnumerable&gt;&gt;(whereBody).Compile(); return whereLambda.Invoke(); } </code></pre>
 

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