我已经搜索了这个,但似乎仍然无法让这个为我工作。我有一个与用户关联的Id数组(他们的组织ID)。它们放在int []中,如下所示:
int[] OrgIds = (from oh in this.Database.OrganizationsHierarchies
join o in this.Database.Organizations on oh.OrganizationsId equals o.Id
where (oh.Hierarchy.Contains(@OrgId))
|| (oh.OrganizationsId == Id)
select o.Id).ToArray();
那里的代码不是很重要,但它表明我从Linq查询中获取了一个整数数组。
但是,我希望运行另一个获取Personnel列表的Linq查询,该代码如下:
List<Personnel> query = (from p in this.Database.Personnels
where (search the array)
select p).ToList();
我想在where子句中添加一种方法,只选择数组中具有OrganizationId的用户。所以,在SQL中,我会做“像OrganizationId ='12'或OrganizationId ='13'或OrganizatonId = '17'的事情。”
我可以在Linq / .NET中相当容易地做到这一点吗?
答案 0 :(得分:42)
虽然这可能更适合加入,但您可以使用:
List<Personnel> query =
(from p in this.Database.Personnels
where OrgIds.Contains(p.OrgID) select p).ToList();
这将转换为类似..的SQL
where OrgID in (1,2,...,n)
答案 1 :(得分:6)
使用Contains
方法进行检查应该可以在这里完成工作。
var query = (from p in this.Database.Personnels
where OrgIds.Contains(p.OrganisationId)
select p).ToList();
答案 2 :(得分:2)
我想让Adam对答案给予赞誉,但我也想分享我用来完成这项工作的代码:
List<int> OrgIds= (from oh in this.Database.OrganizationsHierarchies
join o in this.Database.Organizations on oh.OrganizationsId equals o.Id
where (oh.Hierarchy.Contains(@OrgId))
|| (oh.OrganizationsId == Id)
select o.Id).ToList();
List<Personnel> query = (from p in this.Database.Personnels
where (OrgIds.Contains(p.OrganizationId))
select p).ToList();
-Matt
答案 3 :(得分:1)
会是这样的, OrgIds.ToList.Contains(p.OrginizationID)
虽然我真的会这样做:
var OrgIds = (from oh in this.Database.OrganizationsHierarchies
join o in this.Database.Organizations on oh.OrganizationsId equals o.Id
where (oh.Hierarchy.Contains(@OrgId))
|| (oh.OrganizationsId == Id)
select o.Id);
List<Personnel> query = (from p in this.Database.Personnels
where (OrgIds.Contains(p.OrigizationID)
select p).ToList();
这样,获取人员的最终查询将包含来自两者的组合查询。