Let’s say we have a collection of Person objects
class Person
{
public string PersonName {get;set;}
public string PersonAddress {get;set;}
}
And somewhere in the code defined collection
List<Person> pesonsList = new List<Person>();
We need to have a filter that need to filter the collection and return the result to the end user. Let’s say we have a collection of Filter type objects
class Filter
{
public string FieldName {get;set;}
public string FilterString {get;set;}
}
And somewhere in the code we have
List<Filter> userFilters = new List<Filter>();
So we need to filter the content of the personsList collection by filters defined in the userFilters collection. Where the Filter.FieldName == “PersonName” || Filter.FieldName == “PersonAddress”. How can I do that with LINQ in a cool way ? The solutions like switch/case, or
may be, I thought, extension method on personsList that determines from the FiledName the property of the Person to look into, are known. Something else ? Something tricky:)
Thank you.
You can build a lambda expression to create a proper predicate using the
Expressionclass.With this helper method, you can create an extension method on any
IQueryable<T>class, so this should work for every LINQ backend:…which you can call like this:
If you want to support
IEnumerable<T>collections as well, you’ll need to use this extra extension method:Note that this only works for string properties. If you want to filter on fields, you’ll need to change
Expression.PropertyintoExpression.Field(orMakeMemberAccess), and if you need to support other types than string properties, you’ll have to provide more type information to theExpression.Constantpart of theCreateFilterExpressionmethod.