The method of conditional splicing of C #
In this article, the editor introduces "the method of conditional splicing of C#" in detail, the content is detailed, the steps are clear, and the details are handled properly. I hope this article of "the method of conditional splicing of C#" can help you solve your doubts. Let's go deep into the train of thought of the editor and learn new knowledge together.
Use the code
Special note: when splicing conditions, the condition strID,strBir used must be independent
Var predicate = PredicateBuilder.GetTrue (); predicate = predicate.And (it = > it.id.ToString (). Contains (strID)); predicate = predicate.And (it = > it.Birthday.ToString (). Contains (strBir)); predicate = predicate.And (it = > it.Sex.ToString (). Contains (strSex)); predicate = predicate.And (it = > it.Age = 20); var lst = db.Queryable.Where (predicate). ToList ()
Tool class
Using System;using System.Linq.Expressions;namespace WindowsFormsApp1.Tools {public static class PredicateBuilder {public static Expression GetTrue () {return f = > true;} public static Expression GetFalse () {return f = > false;} public static Expression And (this Expression first, Expression second) {return first.AndAlso (second, Expression.AndAlso) } public static Expression Or (this Expression first, Expression second) {return first.AndAlso (second, Expression.OrElse);} private static Expression AndAlso (this Expression expr1, Expression expr2, Func func) {var parameter = Expression.Parameter (typeof (T)); var leftVisitor = new ReplaceExpressionVisitor (expr1.Parameters [0], parameter); var left = leftVisitor.Visit (expr1.Body) Var rightVisitor = new ReplaceExpressionVisitor (expr2.Parameters [0], parameter); var right = rightVisitor.Visit (expr2.Body); return Expression.Lambda (func (left, right), parameter);} private class ReplaceExpressionVisitor: ExpressionVisitor {private readonly Expression _ oldValue; private readonly Expression _ newValue Public ReplaceExpressionVisitor (Expression oldValue, Expression newValue) {_ oldValue = oldValue; _ newValue = newValue;} public override ExpressionVisit (Expression node) {if (node = = _ oldValue) return _ newValue; return base.Visit (node) After reading this, the article "the method of conditional splicing of C#" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself to understand it. If you want to know more about related articles, welcome to follow the industry information channel.