Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 555
Jonathan Wood Avatar asked Sep 03 '13 23:09

Jonathan Wood


1 Answers

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)) 
like image 149
p.s.w.g Avatar answered Sep 22 '22 12:09

p.s.w.g