查看本文以执行所需的操作:
http :
//www.albahari.com/nutshell/predicatebuilder.aspx
这就像梦一样。我实质上是剪切并粘贴了他们的代码,然后将其取回来(当然是用我自己的数据方案):
SELECt [t0].[Id], [t0].[DateCreated], [t0].[Name] ...FROM [dbo].[Companies] AS [t0]WHERe ([t0].[Name] LIKE @p0) OR ([t0].[Name] LIKE @p1)
这是我为概念验证而运行的代码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Linq.expressions;namespace PredicateTest{class Program{ static void Main(string[] args) { DataClasses1DataContext dataContext = new DataClasses1DataContext(); Program p = new Program(); Program.SearchCompanies("test", "test2"); var pr = from pi in dataContext.Companies.Where(Program.SearchCompanies("test", "test2")) select pi; } DataClasses1DataContext dataContext = new DataClasses1DataContext(); public static expression<Func<Company, bool>> SearchCompanies( params string[] keywords) { var predicate = PredicateBuilder.False<Company>(); foreach (string keyword in keywords) { string temp = keyword; predicate = predicate.Or(p => p.Name.Contains(temp)); } return predicate; }}public static class PredicateBuilder{ public static expression<Func<T, bool>> True<T>() { return f => true; } public static expression<Func<T, bool>> False<T>() { return f => false; } public static expression<Func<T, bool>> Or<T>(this expression<Func<T, bool>> expr1, expression<Func<T, bool>> expr2) { var invokedExpr = expression.Invoke(expr2, expr1.Parameters.Cast<expression>()); return expression.Lambda<Func<T, bool>> (expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); } public static expression<Func<T, bool>> And<T>(this expression<Func<T, bool>> expr1, expression<Func<T, bool>> expr2) { var invokedExpr = expression.Invoke(expr2, expr1.Parameters.Cast<expression>()); return expression.Lambda<Func<T, bool>> (expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters); }}}我建议去该网站获取代码和解释。
(我留下第一个答案,因为如果您需要一个IN语句,它会很好地工作)



