简体   繁体   English

具有简单列表的对象的C#筛选器列表

[英]C# Filter List of Objects With a Simple List

Quite new to LINQ here and I am wondering how to achieve this. LINQ在这里相当陌生,我想知道如何实现这一点。 I have the following codes: 我有以下代码:

var allOrgs = (from org in this.Context.Organizations select org).ToList();

var childOrgs = (from oc in this.Context.OrganizationChild select oc).ToList();

var parentOrgs = (from op in this.Context.OrganizationParent select op).ToList();

the return values for each variable as follows: 每个变量的返回值如下:

allOrgs = [{id=1}, {id=2}, {id=3}, {id=4}];
childOrgs = [{id=2}];
parentOrgs = [{id=3}];

I want to filter the allOrgs such that only those items that are not in the childOrgs or parentOrgs would be returned, ie 我想过滤allOrgs,以便只返回不在childOrgs或parentOrgs中的那些项,即

filteredList = [{id=1}, {id=4}];

I have the following LINQ filter (which I need some help with): 我有以下LINQ过滤器(需要一些帮助):

var filteredList = allOrgs.Where(a => childOrgs.Any(c => c.id != a.id));

filteredList = filteredList.Where(f => parentOrgs.Any(p => p.id != f.id));

return filteredList.ToList();

For some reason, I still end up getting all the values... 由于某种原因,我仍然最终获得了所有的价值...

Appreciate any insight. 赞赏任何见识。 Thanks! 谢谢!

Just merge the two conditions: 只需合并两个条件:

filteredList = allOrgs.Where(a => !childOrgs.Any(c => c.id == a.id)
                               && !parentOrgs.Any(c => c.id == a.id) 
                            );

Note that your original query is backwards - it is looking for all orgs where any parent or child org doesn't match. 请注意,您原来的查询是向后的-它正在寻找任何父级或子级组织都不匹配的组织。

您可以为此使用Except

var filteredList = allOrgs.Except(parentOrgs).Except(childOrgs).ToList();

Adding on to @DStanley Answer ... 添加到@DStanley答案 ...

You can also do: 可以:

var filteredList = allOrgs.Where(a => !childOrgs.Select(r => r.id).Contains(a.id)
                                    && !parentOrgs.Select(r => r.id).Contains(a.id));

Here is a DEMO 这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM