filtering a list using LINQ

leora picture leora · Feb 23, 2011 · Viewed 99.2k times · Source

i have a list of project objects:

IEnumerable<Project> projects

a Project class as a property called Tags. this is a 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};

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).

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 ??

Answer

Dyppl picture Dyppl · Feb 23, 2011

EDIT: better yet, do it like that:

var filteredProjects = 
    projects.Where(p => filteredTags.All(tag => p.Tags.Contains(tag)));

EDIT2: 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.


Probably Intersect is the way to go:

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;
}

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.