Kumar Gaurav
Kumar Gaurav

Reputation: 939

Cannot implicitly convert type System.Collections.Generic.List<IEnumerable> to <IEnumerable

I have two classes Employee and Territory:

public class Territory
{        
    public string TerritoryID { get; set; }
    public string TerritoryDescription { get; set; }       
    public IEnumerable<Employee> Employees { get; set; }
}

I am trying to pull Employees by TerritoryID using LINQ and getting exception:

IEnumerable<Employee> empList = context.Territories
  .Where(x => x.TerritoryID == territoryID)
  .Select(y => y.Employees)
  .ToList();

Exception is:

Cannot implicitly convert type System.Collections.Generic.List<System.Collections.Generic.IEnumerable<Employee>> to System.Collections.Generic.IEnumerable<Employee>. An explicit conversion exists.

Upvotes: 1

Views: 7183

Answers (1)

Irwene
Irwene

Reputation: 3035

You need to use the SelectMany() method instead of Select()

What you are doing here with Select() is creating a new Enumerable containing all the Employees Collections.

SelectMany flattens all the 'child' collections and aggregate every employee into a single Enumerable.


For the second problem, described in the comments, it seems that Employees is not known in the Table Schema or as a Navigation Property.

One fix would be to call ToList() before the SelectMany() call to ensure the SQL query is executed and the remaining operations are executed in-memory.

This is based on this SO Post

Upvotes: 5

Related Questions