Linq query with Array in where clause?

前端 未结 4 977
无人共我
无人共我 2020-12-28 16:23

I have searched for this, but still can\'t seem to get this to work for me. I have an array of Id\'s associated with a user (their Organization Id). These are placed in an

相关标签:
4条回答
  • 2020-12-28 17:00

    I wanted to give Adam credit for the answer, but I also wanted to share the code I used to make this work:

    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();
    

    Thanks all,

    -Matt

    0 讨论(0)
  • 2020-12-28 17:02

    A check using the Contains method should do the job here.

    var query = (from p in this.Database.Personnels
                 where OrgIds.Contains(p.OrganisationId)
                 select p).ToList();
    
    0 讨论(0)
  • 2020-12-28 17:09

    It would be something like this, OrgIds.ToList.Contains(p.OrginizationID)

    Though really I would do it more like this:

    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();
    

    That way the final query to get personnel will execute containing the combined query from both.

    0 讨论(0)
  • 2020-12-28 17:15

    While this is probably better suited to a join, you can use this:

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

    This will translate into SQL something like..

    where OrgID in (1,2,...,n)
    
    0 讨论(0)
提交回复
热议问题