36
votes

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

1 Answers

56
votes

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))