Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq query with Array in where clause?

Tags:

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 int[] as follows:

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

The code there isn't very important, but it shows that I am getting an integer array from a Linq query.

From this, though, I want to run another Linq query that gets a list of Personnel, that code is as follows:

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

I want to add in the where clause a way to select only the users with the OrganizationId's in the array. So, in SQL where I would do something like "where OrganizationId = '12' or OrganizationId = '13' or OrganizatonId = '17'."

Can I do this fairly easily in Linq / .NET?

like image 801
Matt Dell Avatar asked May 07 '09 19:05

Matt Dell


People also ask

Can we use array in Where clause?

We can pass an array with the help of where IN clause.

Can LINQ query work with array?

LINQ allows us to write query against all data whether it comes from array, database, XML etc.

Which of the following are the conversion operators in LINQ?

The Conversion operators in LINQ are useful in converting the type of the elements in a sequence (collection). There are three types of conversion operators: As operators (AsEnumerable and AsQueryable), To operators (ToArray, ToDictionary, ToList and ToLookup), and Casting operators (Cast and OfType).

Which of the following clauses can be used to end a LINQ query expression?

LINQ query syntax always ends with a Select or Group clause.


2 Answers

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) 
like image 158
Adam Robinson Avatar answered Oct 22 '22 10:10

Adam Robinson


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(); 
like image 31
Noldorin Avatar answered Oct 22 '22 11:10

Noldorin