filtering a list using LINQ

后端 未结 5 1456
面向向阳花
面向向阳花 2020-12-09 14:38

i have a list of project objects:

IEnumerable projects

a Project class as a property called Tags

5条回答
  •  暖寄归人
    2020-12-09 14:56

    We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags. So we can use Linq Except to get those tags which are not included. Then we can use Count() == 0 to have only those which excluded no tags:

    var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);
    

    Or we can make it slightly faster with by replacing Count() == 0 with !Any():

    var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());
    

提交回复
热议问题