LINQ:如何在查询中重写WHERE子句?

时间:2011-11-17 23:28:51

标签: asp.net linq where-clause

我简单的一个关键字查询的工作原理如下:

   var query = from product in dc.catalog 
                        where product.Name.Contains("table")
                        select product;

我希望在查询中提供更大的灵活性,并从文本框中获取关键字,这些关键字可以来自“table red round”这样的字符串。在这里,我希望结果包含所有3个单词(红色,圆形,表格)的记录。

如何重写WHERE子句来处理这个问题?感谢。

4 个答案:

答案 0 :(得分:2)

这个怎么样(只是注意到你想要所有):

var query = from product in dc.catalog 
            where textBox.Text.Split(' ').All(s => product.Name.Contains(s))
            select product;

答案 1 :(得分:2)

var a = from product in dc.catalog  
            where textbox1.Text.Split(' ').All(nam => product.Name.Contains(nam)) 
            select product; 

答案 2 :(得分:1)

// You can produce these matches using any method (string.Split, e.g.)
// Just make sure that they're an array or a list.
var matches = new[]{"table", "red", "round"};
var query = from product in dc.catalog 
            where matches.All(m => product.Name.Contains(m))
            select product;

答案 3 :(得分:1)

查看Except函数

e.g。

var query = from product in dc.catalog 
                    where !selectedItems.Except(product.Name).Any()
                    select product;
相关问题