简体   繁体   English

LINQ Any()不能按预期工作

[英]LINQ Any() not working as expected

I'm battling with what I thought would be a simple query... 我正在与我认为将是一个简单查询的问题作斗争...

Schema is like : 架构就像

Documents (DocumentID, Name) Documents (文件ID,名称)
Industries (IndustryID, Name) Industries (IndustryID,名称)
Documents_Industries (DocumentID, IndustryID) Documents_Industries (文档ID,行业ID)

Data is like : 数据就像

DocA -- IndustryA DocA-IndustryA
DocB -- IndustryA, IndustryB DocB-IndustryA,IndustryB
DocC -- IndustryA, IndustryB DocC-IndustryA,IndustryB
DocD -- IndustryB DocD-IndustryB

(So the data above would result in 6 rows in Documents_Industries , hopefully that's self-explanatory) (因此,上面的数据将在Documents_Industries产生6行,希望这是不言而喻的)

Expected behaviour : I'm trying to show a list of Documents, filtered by the Industry(ies) a user selects. 预期的行为 :我正在尝试显示一个文档列表,该列表由用户选择的行业过滤。 If IndustryA is selected, result set should be DocA, DocB, DocC. 如果选择了IndustryA,则结果集应为DocA,DocB,DocC。 If IndustryB is selected, result set should be DocB, DocC, DocD. 如果选择了IndustryB,则结果集应为DocB,DocC,DocD。 If IndustryA and IndustryB is selected, result set should be DocB, DocC. 如果选择了IndustryA和IndustryB,则结果集应为DocB,DocC。

Code so far : 到目前为止的代码

IEnumerable<Document> docs = db.Documents.Where(l => l.IsActive == true);

// industryIdsSelected is an int[] from the user's selection

if (industryIdsSelected.Length > 0)
{
    docs = docs.Where(l => l.Industries.Any(m => industryIdsSelected.Contains(m.IndustryID)));
}

Actual behaviour : If IndustryA and IndustryB is selected, result set is DocA, DocB, DocC, DocD. 实际行为 :如果选择了IndustryA和IndustryB,则结果集为DocA,DocB,DocC,DocD。 Instead of just DocB, DocC. 不仅仅是DocB,还有DocC。

I've tried with .All() but that doesn't work either. 我已经尝试过.All()但这也不起作用。 What could I be doing wrong? 我可能做错了什么?

您需要像这样同时使用AllAny

docs.Where(l => industryIdsSelected.All(x => l.Industries.Any(m => m.IndustryID == x)));

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

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