我有一个List
试过这个(不起作用):
items = from dbt in database.Items where (stringList.FindAll(s => dbt.Text.Contains(s)).Count > 0) select dbt;
查询将类似于:
select * from items where text like '%string1%' or text like '%string2%'
这可能吗?
查看这篇文章,做你想做的事:
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> SearchCompanies( params string[] keywords) { var predicate = PredicateBuilder.False (); 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 > 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); } } }
我建议去网站查看代码和解释.
(我要留下第一个答案,因为如果你需要一个IN声明它会很好用)
整个LINQ to SQL游戏的新功能,但这种语法有帮助吗?
string[] items = new string[] { "a", "b", "c", "d" }; var items = from i in db.Items where items.Contains(p.text) select i;
得到它:
http://blog.wekeroad.com/2008/02/27/creating-in-queries-with-linq-to-sql/