Contact Form

Name

Email *

Message *

Build Where Clause Dynamically Using Linq PredicateBuilder to filter data from DataTable C#

No comments
To filter some data from a DataTable based on two or more condition is not possible using the below code. As the Linq where condition not allowed more than one condition.
  1. var filtered = dataTable.Where(x => x["Name"].Equals("Venkat") && x => x["Age"].Equals("26")).ToList()

So using the PredicateBuilder we can build where clause dynamically. Check the below code.,
As you can see, the below code is constructing the where clause dynamically. You can pass multiple column name and value as filter condition dynamically. 
  1. var predicate = PredicateBuilder.True();
  2. predicate = predicate.And(x => x["Name"].Equals("Venkat"));
  3. predicate = predicate.And(x => x["Age"].Equals("26"));
  4. predicate.Compile();
  5. var filtered = dataTable.Where(predicate).ToList();

  1. public static class PredicateBuilder
  2. {
  3. public static Expression<Func<T, bool>> True<T>()
  4. {
  5. return f => true;
  6. }
  7.  
  8. public static Expression<Func<T, bool>> False<T>()
  9. {
  10. return f => false;
  11. }
  12.  
  13. public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
  14. {
  15. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
  16. return Expression.Lambda<Func<T, bool>> (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
  17. }
  18.  
  19. public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
  20. {
  21. var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
  22. return Expression.Lambda<Func<T, bool>> (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
  23. }
  24. }

No comments :

Post a Comment