c# - 基于 IEnumerable<string> 过滤项目

标签 c# linq

我有一个项目列表,其属性 (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/

相关文章:

c# - 如何使用Any()而不是RemoveAll()来排除列表项?

c# - 如何使用 C# 对组合框进行 Linq 查询

c# - 找到两个数组之间差异的更好方法

c# - EF 连接字符串错误

c# - LINQ:根据最新时间通过选定的 ID 获取唯一行

c# - 无法读取数据驱动测试的 csv 文件的第一列。 Visual Studio 2017

c# 返回属性的串联

asp.net-mvc - 使用 Linq to Sql 选择多个表

c# - 如何期望类的属性类型作为泛型函数中的参数?

c# - 尝试使用 Hangfire 时的自引用循环