在where子句中使用Array查询Linq?

Mat*_*ell 22 .net sql linq

我已经搜索过这个,但似乎仍然无法让这个为我工作.我有一个与用户关联的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();
Run Code Online (Sandbox Code Playgroud)

那里的代码不是很重要,但它表明我从Linq查询中获取了一个整数数组.

但是,我希望运行另一个获取Personnel列表的Linq查询,该代码如下:

List<Personnel> query = (from p in this.Database.Personnels
                                where (search the array)
                                select p).ToList();
Run Code Online (Sandbox Code Playgroud)

我想在where子句中添加一种方法来只选择数组中具有OrganizationId的用户.所以,在SQL中,我会做"像OrganizationId ='12'或OrganizationId ='13'或OrganizatonId = '17'的事情."

我可以在Linq/.NET中相当容易地做到这一点吗?

Ada*_*son 42

虽然这可能更适合加入,但您可以使用:

List<Personnel> query = 
    (from p in this.Database.Personnels 
    where OrgIds.Contains(p.OrgID) select p).ToList();
Run Code Online (Sandbox Code Playgroud)

这将转化为SQL之类的东西......

where OrgID in (1,2,...,n)
Run Code Online (Sandbox Code Playgroud)


Nol*_*rin 6

使用该Contains方法的检查应该在这里完成工作.

var query = (from p in this.Database.Personnels
             where OrgIds.Contains(p.OrganisationId)
             select p).ToList();
Run Code Online (Sandbox Code Playgroud)