-4

[Sorry if it is a duplicate] I couldn't find properly solution, so I decided to ask a question.

I have an object companies which returns list of elements.

I would like to write a query which will select these all CompanyId which we have in our list. I don't want to select only one record by using FirstOrDefault().

Example:

var companiesSummary = _context.Company
                       .Where(c => c.CompanyId == companies.Select(cs => cs.ID))
                       .Include(country => country.Country)                   

How can I cope with it? Do you have any ideas?

Piotr Podyma
  • 11
  • 1
  • 2
  • 6

3 Answers3

1

Select the ids of the companies from your in-memory list and then pass that into the query in the where method:

var ids = companies.Select(cs => cs.ID).ToList();
var companiesSummary = 
    _context.Company
    .Where(c => ids.contains(c.ID))
    .Include(country => country.Country)
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
0

Assuming your companies contains a list of objects with an ID property you want to compare to Company.CompanyId, your query should look like

int[] ids = companies.Select(cs => cs.ID).ToArray();
var companiesSummary = _context.Company
    .Where(c => ids.Contains(c.CompanyId))
    .Include(company => company.Country);
Tsahi Asher
  • 1,767
  • 15
  • 28
-1
var matchingCompanies = companies.Where(c => companyIds.Contains(c.Id))

Make companyIds a HashSet<T> for an efficient Contains.

George Helyar
  • 4,319
  • 1
  • 22
  • 20