filtering a list using LINQ(使用 LINQ 过滤列表)
问题描述
我有一个项目对象列表:
i have a list of project objects:
IEnumerable<Project> projects
一个 Project 类作为一个名为 Tags 的属性.这是一个 int[]
a Project class as a property called Tags. this is a int[]
我有一个名为 filteredTags 的变量,它也是一个 int[].
i have a variable called filteredTags which is also a int[].
假设我的过滤标签变量如下所示:
So lets say my filtered tags variable looks like this:
int[] filteredTags = new int[]{1, 3};
我想过滤我的列表 (projects) 以仅返回具有过滤器中列出的所有标签的项目(在这种情况下,标签中至少有标签 1 和标签 3 属性).
I want to filter my list (projects) to only return projects that have ALL of the tags listed in the filter (in this case at least tag 1 AND tag 3 in the Tags property).
我试图使用 Where() 和 Contains() 但这似乎只有在我与单个值进行比较时才有效.我将如何将一个列表与另一个列表进行比较,在该列表中我需要匹配过滤列表中的所有项目??
I was trying to use Where() and Contains() but that only seems to work if i am comparing against a single value. How would i do this to compare a list against another list where i need a match on all the items in the filtered list ??
推荐答案
更好的是,这样做:
var filteredProjects =
projects.Where(p => filteredTags.All(tag => p.Tags.Contains(tag)));
老实说,我不知道哪个更好,所以如果性能不重要,请选择您认为更具可读性的那个.如果是,您必须以某种方式对其进行基准测试.
Honestly, I don't know which one is better, so if performance is not critical, choose the one you think is more readable. If it is, you'll have to benchmark it somehow.
可能 Intersect
是要走的路:
void Main()
{
var projects = new List<Project>();
projects.Add(new Project { Name = "Project1", Tags = new int[] { 2, 5, 3, 1 } });
projects.Add(new Project { Name = "Project2", Tags = new int[] { 1, 4, 7 } });
projects.Add(new Project { Name = "Project3", Tags = new int[] { 1, 7, 12, 3 } });
var filteredTags = new int []{ 1, 3 };
var filteredProjects = projects.Where(p => p.Tags.Intersect(filteredTags).Count() == filteredTags.Length);
}
class Project {
public string Name;
public int[] Tags;
}
虽然一开始看起来有点难看.如果您不确定它们在列表中是否都是唯一的,您可以先将 Distinct
应用到 filteredTags
,否则计数比较将无法按预期进行.
Although that seems a little ugly at first. You may first apply Distinct
to filteredTags
if you aren't sure whether they are all unique in the list, otherwise the counts comparison won't work as expected.
这篇关于使用 LINQ 过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 LINQ 过滤列表


- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01