Search code examples
c#linq

IN Operator between 2 collection objects


In Sql, I know we have the IN operator and the equivalent of that is .Contains() in LINQ but i am stuck on one problem here

Consider the following linq query:

_dbContext.Offices.Where(o => o.Id == policy.OfficeId).FirstOrDefaultAsync()

Suppose i were to introduce a policies (plural) object which is a collection object each policy in the collection has its own officeId, how do I check if the offices collection consists of the officesId from policies collection object? I would like to do this in method syntax if possible. Thanks in advance.


Solution

  • Without having access to your data model, your answer does seem plausible; however, you need to have a call to .ToListAsync() at the end for this to compile. Also, it's more efficient to use Any() (rather than .Select.Contains):

    await _dbContext.Offices.Where(o => policies.Any(p => p.OfficeId == o.Id)).ToListAsync();
    

    I'm not sitting in front of a compiler, but if you just want the first one, the following is even better IIRC:

    await _dbContext.Offices.FirstOrDefaultAsync(o => policies.Any(p => p.OfficeId == o.Id));