How to write string.Contains(someText) in expression Tree

前端 未结 2 1556
离开以前
离开以前 2021-01-21 06:19

This is the tutorial I\'m following to learn Expression Tree.

I\'ve more than 35 columns to display, but the user can chose to display 10 columns at once. So one the use

2条回答
  •  无人及你
    2021-01-21 07:11

    I like the PredicateBuilder class for stuff like this scenario:

    using System;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Collections.Generic;
    
    public static class PredicateBuilder
    {
      public static Expression> True ()  { return f => true;  }
      public static Expression> False () { return f => false; }
    
      public static Expression> Or (this Expression> expr1,
                                                          Expression> expr2)
      {
        var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
        return Expression.Lambda>
              (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
      }
    
      public static Expression> And (this Expression> expr1,
                                                           Expression> expr2)
      {
        var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
        return Expression.Lambda>
              (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
      }
    }
    

    Code using this would look like:

    var predicate = PredicateBuilder.True().And(i=>i.Id==id);
    if(!string.IsNullOrEmpty(searchText))
    {
        if (firstNameColumnVisible) {
           predicate = predicate.And(i=>i.FirstName.Contains(searchText));
        }
        if (lastNameColumnVisible) {
           predicate = predicate.And(i=>i.LastName.Contains(searchText));
        }
        // more columns here.
    }
    

    At the end, use the PredicateBuilder instance as arguments to your Where operator in the Linq query.

提交回复
热议问题