Creating a Predicate Builder extension method
Posted
by
Rippo
on Programmers
See other posts from Programmers
or by Rippo
Published on 2012-11-22T13:55:35Z
Indexed on
2012/11/22
17:10 UTC
Read the original article
Hit count: 165
design-patterns
I have a Kendo UI Grid that I am currently allowing filtering on multiple columns. I am wondering if there is a an alternative approach removing the outer switch statement?
Basically I want to able to create an extension method so I can filter on a IQueryable<T>
and I want to drop the outer case statement so I don't have to switch column names.
private static IQueryable<Contact> FilterContactList(FilterDescriptor filter, IQueryable<Contact> contactList)
{
switch (filter.Member)
{
case "Name":
switch (filter.Operator)
{
case FilterOperator.StartsWith:
contactList = contactList.Where(w => w.Firstname.StartsWith(filter.Value.ToString()) || w.Lastname.StartsWith(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).StartsWith(filter.Value.ToString()));
break;
case FilterOperator.Contains:
contactList = contactList.Where(w => w.Firstname.Contains(filter.Value.ToString()) || w.Lastname.Contains(filter.Value.ToString()) || (w.Firstname + " " + w.Lastname).Contains( filter.Value.ToString()));
break;
case FilterOperator.IsEqualTo:
contactList = contactList.Where(w => w.Firstname == filter.Value.ToString() || w.Lastname == filter.Value.ToString() || (w.Firstname + " " + w.Lastname) == filter.Value.ToString());
break;
}
break;
case "Company":
switch (filter.Operator)
{
case FilterOperator.StartsWith:
contactList = contactList.Where(w => w.Company.StartsWith(filter.Value.ToString()));
break;
case FilterOperator.Contains:
contactList = contactList.Where(w => w.Company.Contains(filter.Value.ToString()));
break;
case FilterOperator.IsEqualTo:
contactList = contactList.Where(w => w.Company == filter.Value.ToString());
break;
}
break;
}
return contactList;
}
Some additional information, I am using NHibernate Linq. Also another problem is that the "Name" column on my grid is actually "Firstname" + " " + "LastName" on my contact entity. We can also assume that all filterable columns will be strings.
© Programmers or respective owner