c# - filtering a list using LINQ -
i have list of project objects:
ienumerable<project> projects
a project class property called tags. int[]
i have variable called filteredtags int[].
so lets filtered tags variable looks this:
int[] filteredtags = new int[]{1, 3};
i want filter list (projects) return projects have of tags listed in filter (in case @ least tag 1 , tag 3 in tags property).
i trying use where() , contains() seems work if comparing against single value. how compare list against list need match on items in filtered list ??
edit: better yet, that:
var filteredprojects = projects.where(p => filteredtags.all(tag => p.tags.contains(tag)));
edit2: honestly, don't know 1 better, if performance not critical, choose 1 think more readable. if is, you'll have benchmark somehow.
probably intersect
way 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 seems little ugly @ first. may first apply distinct
filteredtags
if aren't sure whether unique in list, otherwise counts comparison won't work expected.
Comments
Post a Comment