过滤使用LINQ名单 [英] filtering a list using LINQ

查看:113
本文介绍了过滤使用LINQ名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有项目对象的列表:

 的IEnumerable<项目>项目



项目类作为属性名为标签。这是一个 INT []



我称之为一个变量的 filteredTags 这也是一个 INT [ ] 即可。



因此​​,可以说我的过滤标签变量是这样的:

  INT [] filteredTags =新INT [] {1,3}; 



我要筛选我的列表(项目)只返回项目,这些项目都在过滤器中列出的标签(在这种情况下,至少标签1与在代码属性标记3)。



我是尝试使用其中,()和包含(),但似乎只如果我对一个值进行比较工作。如何将我这样做是为了对抗另一个列表,我需要在过滤列表??


解决方案
<所有项目的匹配比较列表p>编辑:更好的是,做这样的:

  VAR filteredProjects = 
projects.Where(p => ; filteredTags.All(标签=> p.Tags.Contains(标签)));



EDIT2:说实话,我不知道哪一个更好,所以如果性能是不是很关键,选择你认为是更具可读性的人。如果是,你必须基准它在某种程度上。






也许相交是要走的路:

 无效的主要()
{
VAR项目=新的List<项目>();
projects.Add(新项目{名称=PROJECT1,标签= INT新[] {2,5,3,1}});
projects.Add(新项目{名称=Project2的标签= INT新[] {1,4,7}});
projects.Add(新项目{名称=项目3,标签= INT新[] {1,7,12,3}});

变种filteredTags = INT新[] {1,3};
VAR filteredProjects = projects.Where(P => p.Tags.Intersect(filteredTags).Count之间的()== filteredTags.Length);
}


类项目{
公共字符串名称;
公众诠释[]标签;
}



虽然这似乎起初有点难看。你可以先申请鲜明 filteredTags 如果您不能确定他们是否是列表中的所有独特的,否则,算作预期比较将无法工作。


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

解决方案

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.

这篇关于过滤使用LINQ名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆