问题描述
我有一个项目对象列表:
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 过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!