这里对LINQ很新,我想知道如何实现这一目标。我有以下代码:
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();
每个变量的返回值如下:
allOrgs = [{id=1}, {id=2}, {id=3}, {id=4}];
childOrgs = [{id=2}];
parentOrgs = [{id=3}];
我想过滤allOrgs,以便只返回那些不在childOrgs或parentOrgs中的项目,即
filteredList = [{id=1}, {id=4}];
我有以下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();
出于某种原因,我仍然得到了所有的价值......
欣赏任何见解。谢谢!
答案 0 :(得分:3)
只需合并两个条件:
filteredList = allOrgs.Where(a => !childOrgs.Any(c => c.id == a.id)
&& !parentOrgs.Any(c => c.id == a.id)
);
请注意,您的原始查询是向后的 - 它正在查找任何父级或子级组织不匹配的所有组织。
答案 1 :(得分:2)
您可以使用Except
:
var filteredList = allOrgs.Except(parentOrgs).Except(childOrgs).ToList();
答案 2 :(得分:0)
添加到@DStanley Answer ...
你也可以 做:
var filteredList = allOrgs.Where(a => !childOrgs.Select(r => r.id).Contains(a.id)
&& !parentOrgs.Select(r => r.id).Contains(a.id));
这是DEMO