我有一个项目列表,其属性 (ProductNames) 是 IEnumberable<string>
.我如何在属性上过滤此列表,以便我只获得一个列表,其中项目与另一个 IEnumerable<string>
中的所有项目匹配(FilterProductNames)?
我尝试了以下方法,但它似乎返回了在过滤器 IEnumberable 中匹配任何内容(OR 样式匹配)的所有项目:
Items.Where(x => x.ProductNames.Intersect(FilterProductNames).Any())
更新
我尝试使用下面蒂姆的回答,但它似乎给了我一个空集,所以我尝试只使用 FilterProductNames 中的一个项目,但这仍然没有返回任何内容,所以我通过执行以下操作测试了相同的过滤器:
if (count == 1)
{
// this will return me 4 items
Items = Items.Where(x => x.ProductNames.Contains(FilterProductNames.First()));
}
else
{
// when I remove the above if, this will return me 0 items filtering on the same thing
Items = Items.Where(x => x.ProductNames.All(pn => FilterProductNames.Contains(pn)));
// have also tried the other version on tim's answer but to no avail:
// Items = Items.Where(x => !x.ProductNames.Except(FilterProductNames).Any());
}
更新 2
对于造成一些困惑的错误措辞,我深表歉意,我正在寻找包含 FilterProductNames 中所有名称的项目,但不仅限于 FilterProductNames 中的项目,例如,如果我搜索产品名称为 Test 和Test1,它应该带回包含这些名称和任何其他名称的任何项目。
这可能吗?
最佳答案
您可以使用Enumerable.All
:
Items.Where(x => x.ProductNames.All(pn => FilterProductNames.Contains(pn)))
或者 - 可能更有效 - 使用 ! ... 除了.Any
:
Items.Where(x => !x.ProductNames.Except(FilterProductNames).Any());
编辑您的评论/编辑:“...包含 FilterProductNames 中所有名称的所有项目”
然后你必须反转语句:
Items.Where(x => FilterProductNames.All(fp => x.ProductNames.Contains(fp)));
或
Items.Where(x => !FilterProductNames.Except(x.ProductNames).Any());
关于c# - 基于 IEnumerable<string> 过滤项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21827415/