linq其中list包含列表中的所有匹配项

时间:2016-03-24 17:28:14

标签: c# .net linq entity-framework-6

我有三个表Keyword,Product和KeywordProduct。

  • 如果我尝试过滤“the”,请返回A和B产品
  • 如果我尝试过滤“矩阵”,则仅返回B产品

但是当我过滤“矩阵”时,我也得到了B和A.我只需要获得B记录。

这就是代码:

var keywordTermList = ("the matrix").Split(' ');

db.Products
.Where(product => product.ProductKeywords.All(k => keywordTermList.Contains(k.Keyword.Name)))

关键字表

+-----------+---------+
| KeywordId |  Name   |
+-----------+---------+
|         1 | awakens |
|         2 | force   |
|         3 | the     |
|         4 | matrix  |
+-----------+---------+

ProductKeyword表

+------------+-----------+
| KeywordId  | ProductId |
+------------+-----------+
| 3(the)     | A         |
| 2(force)   | A         |
| 1(awakens) | A         |
| 3(the)     | B         |
| 4(matrix)  | B         |
+------------+-----------+

产品表有A和B记录。

我该怎么做?当我过滤“矩阵”时,我怎么才能得到B.

1 个答案:

答案 0 :(得分:0)

如果您希望子集完全匹配超集

var query = products.Where(p => !keywordListTerm.Except(p.ProductKeywords.Select(pk => pk.Name)).Any());

这是完整的例子

public class Program
{
    public static void Main(string[] args)
    {

        Product A = new Product();
        A.Name = "A";
        A.ProductKeywords = new List<Keyword>() { 
            new Keyword(){Name = "the"},
            new Keyword(){Name = "force"},
            new Keyword(){Name = "awakens"}
        };

        Product B = new Product();
        B.Name = "B";
        B.ProductKeywords = new List<Keyword>() { 
            new Keyword(){Name = "the"},
            new Keyword(){Name = "matrix"}
        };

        List<Product> products = new List<Product>() { A, B };

        var keywordListTerm = ("the force matrix").Split(' ');

        var query = products.Where(p => !keywordListTerm.Except(p.ProductKeywords.Select(pk => pk.Name)).Any());

        foreach (var item in query) { 
            Console.WriteLine(item.Name);
        }

        Console.ReadKey();
    }
}

public class Product {
    public string Name = string.Empty;
    public List<Keyword> ProductKeywords;
}

public class Keyword
{
    public string Name;

}

希望这有帮助。