ExpertGenie
ExpertGenie

Reputation: 195

Having multiple Ids on linq-sql join query in c#

I have a linq-to-sql query that fetches records.

First of all, I have a variable that can hold an Id or multiple Ids.

var consumerId = _context.Consumers.Where(x => x.UsrDefault.Equals("True"));
// This can return one or an array of Ids. 

Then, I have a linq-to-sql query as follows:

var query = (from users in _context.Users 
            join consumers in _context.Consumers 
            on usersId equals consumerId 
            select new UserConsumerDto 
            {
             FirstName = users.FirstName, 
             LastName = users.LastName
            }).ToList()

My question is that when I have multiple consumerId, how can I perform this linq-to-sql query ? I want to avoid any foreach loop.

Can someone please advise ?

Upvotes: 2

Views: 1341

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

Contains is the method to be used here or Any().

See the code snippet below:

var query = (from users in _context.Users 
            join consumers in _context.Consumers 
            on users.usersId equals consumers.consumerId 
            where consumerId.Contains(consumers.consumerId)
            select new UserConsumerDto 
            {
             FirstName = users.FirstName, 
             LastName = users.LastName
            }).ToList()

for any :

where consumerId.Any(id => id == consumers.consumerId)

Upvotes: 3

Related Questions