John S
John S

Reputation: 8349

Entity Framework ICollection to List

I am trying to do something like this:

 List<Department> t = db.Employees
        .Where(e => e.CompanyId.Equals(12345))
        .Where(e => e.Departments.Any(d => d.IsActive.Equals(true)))
        .Select(e => e.Departments);

But it gives me an error telling me that can't implicitly convert from IQueryable<ICollection<Department>> to List<Department>.

My Linq is a bit rusty. What is the right way to bring this down to the List<Department>

Upvotes: 1

Views: 1453

Answers (1)

David L
David L

Reputation: 33873

You have a queryable collection of a collection of departments (note the plural e.Departments). As a result, you can use .SelectMany() to flatten your collection and then resolve the IQueryable with .ToList().

List<Department> t = db.Employees
    .Where(e => e.CompanyId.Equals(12345))
    .Where(e => e.Departments.Any(d => d.IsActive.Equals(true)))
    .SelectMany(e => e.Departments).ToList();

Upvotes: 2

Related Questions