簡體   English   中英

linq,其中list包含列表中所有匹配項

[英]linq where list contains all matched in list

我有三個表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  |
+-----------+---------+

產品關鍵字表

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

產品表具有A和B記錄。

我將如何處理? 過濾“矩陣”時,如何只得到B。

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

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;

}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM