private IQueryable<Customer> FilterResult(string search, List<Customer> dtResult, List<string> columnFilters)
{
IQueryable<Customer> results = dtResult.AsQueryable();
results = results.Where(p =>
(
search == null ||
(
p.Name != null && p.Name.ToLower().Contains(search.ToLower())
|| p.City != null && p.City.ToLower().Contains(search.ToLower())
|| p.Postal != null && p.Postal.ToLower().Contains(search.ToLower())
|| p.Email != null && p.Email.ToLower().Contains(search.ToLower())
|| p.Company != null && p.Company.ToLower().Contains(search.ToLower())
|| p.Account != null && p.Account.ToLower().Contains(search.ToLower())
|| p.CreditCard != null && p.CreditCard.ToLower().Contains(search.ToLower())
)
)
&& (columnFilters[0] == null || (p.Name != null && p.Name.ToLower().Contains(columnFilters[0].ToLower())))
&& (columnFilters[1] == null || (p.City != null && p.City.ToLower().Contains(columnFilters[1].ToLower())))
&& (columnFilters[2] == null || (p.Postal != null && p.Postal.ToLower().Contains(columnFilters[2].ToLower())))
&& (columnFilters[3] == null || (p.Email != null && p.Email.ToLower().Contains(columnFilters[3].ToLower())))
&& (columnFilters[4] == null || (p.Company != null && p.Company.ToLower().Contains(columnFilters[4].ToLower())))
&& (columnFilters[5] == null || (p.Account != null && p.Account.ToLower().Contains(columnFilters[5].ToLower())))
&& (columnFilters[6] == null || (p.CreditCard != null && p.CreditCard.ToLower().Contains(columnFilters[6].ToLower())))
);
return results;
}
This is the method which I am using for datatable filter , Here my question is can I make it as generic ? I feel it can be using reflection. But does that affect to performance as well ?
thx in advance..
I have done till it so far :
private IQueryable<T> FilterResult<T>(string search, IQueryable<T> dtResult, List<string> columnFilters)
{
IQueryable<T> results = dtResult;
Type typeParameterType = typeof(T); // this will give me the class detail which I have passed
// 1 How to extract all property of this class to use in where clause
// 2 How I can use it either dynamic linq , foreach or any possible solution.
//1
PropertyInfo[] properties = typeParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var item in properties)
{
// This will be changed after some validation logic
string predicate = item.Name + " = " + search;
results = results.Where(predicate);
}
return results;
}