简体   繁体   English

Linq查询返回匹配数组中所有单词的行

[英]Linq Query returning rows matching all words in array

I need to build a query using linq to return the rows matching all words in an array: 我需要使用linq构建查询以返回与数组中所有单词匹配的行:

Example array (splitKeywords): 示例数组(splitKeywords):

{string[2]}
    [0]: "RENAULT"
    [1]: "CLIO"

KeywordSearch table: 关键字搜索表:

public class KeywordSearch
{
    // Primary properties
    public int Id { get; set; }
    public string Name { get; set; }
    public Keyword Keyword { get; set; }
}

This table has the records: 该表具有记录:

Id: 1
Name: "RENAULT"
Keyword_Id: 3503

Id: 2
Name: "CLIO"
Keyword_Id: 3503

I want to get all the Keyword_Id s which match all the words in the array. 我想获取所有与数组中所有单词匹配的Keyword_Id

So far I have: 到目前为止,我有:

EDIT: 编辑:

var keywordSearchQuery = _keywordSearchRepository.Query;

var keywordIds = from k in keywordSearchQuery
                        where splitKeywords.All(word => word.Equals((k.Name)))
                        select k.Keyword.Id;

But It's not working. 但这不起作用。 Any ideas? 有任何想法吗?

Thanks 谢谢

First you need to combine all of the records with the same Keyword.Id into a single record. 首先,您需要将所有具有相同Keyword.Id的记录合并到一条记录中。 Do that with GroupBy. 使用GroupBy做到这一点。
Once you have them grouped, you can filter out the groups (KeywordIds), where all of the items (the individual records, the names), don't match at least one of the splitKeyWords. 将它们分组后,您可以过滤出组(KeywordId),其中所有项目(各个记录,名称)都与至少一个splitKeyWords不匹配。

Original - This checks that all Name values match a value in splitKeyWords 原始 -检查所有Name值是否与splitKeyWords中的值匹配

var results = keywordSearchQuery
                .GroupBy(k => k.Keyword_Id)
                .Where(g => g.All(k => splitKeyWords.Any(w => w.Equals(k.Name))))
                .Select(g => g.Key);

Updated - This checks that all values in splitKeyWords match a Name. 已更新 -这将检查splitKeyWords中的所有值是否与名称匹配。

var results = keywordSearchQuery
                .GroupBy(k => k.Keyword_Id)
                .Where(g => splitKeyWords.All(w => g.Any(k => w.Equals(k.Name))))
                .Select(g => g.Key);

Note that if you have a Keyword.Id with names RENAULT, CLIO, and ASDF, it will match. 请注意,如果您有一个名称为RENAULT,CLIO和ASDF的Keyword.Id,它将匹配。

This will go through your array and find the matching key for each element, if this is what you're looking for? 如果您要查找的是数组,它将遍历数组并找到每个元素的匹配键?

var ids splitKeywords.Select(k => keywordSearchQuery.Single(q => q.Name == k).Id).ToArray();

You'd have to do a bit more validation if the Name wasn't unique or if you weren't sure you'd get a match. 如果名称不是唯一的,或者不确定是否会匹配,则必须做更多的验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM