SelectMany() Cannot Infer Type Argument -- Why Not?

c# entity-framework linq

Question

I have an Employee table and an Office table. These are joined in a many-to-many relationship via the EmployeeOffices table.

I'd like to get a list of all the offices a particular employee (CurrentEmployee) is associated with.

I thought I could do something like this:

foreach (var office in CurrentEmployee.EmployeeOffices.SelectMany(eo => eo.Office))
    ;

But this gives me the error:

The type arguments for method 'System.Linq.Enumerable.SelectMany(System.Collections.Generic.IEnumerable, System.Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I understand I could add type arguments. But Intellisense recognizes that eo.Office is of type Office. So why isn't this clear to the compiler?

1
27
9/3/2013 11:25:05 PM

Accepted Answer

The type returned by the delegate you pass to SelectMany must be an IEnumerable<TResult>, but evidently, Office doesn't implement that interface. It looks like you've simply confused SelectMany for the simple Select method.

  • SelectMany is for flattening multiple sets into a new set.
  • Select is for one-to-one mapping each element in a source set to a new set.

I think this is what you want:

foreach (var office in CurrentEmployee.EmployeeOffices.Select(eo => eo.Office))
48
9/4/2013 3:51:31 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow