3

I would like to get collection or list of Item objects, but I get array of arrays now.

Item[][] s = employees.Select(e => e.Orders.Select(o => new Item(e.ID, o.ID)).ToArray()).ToArray();

Can anyone select me solution to do it?

P.S. just LinQ solution :)

Maxim Polishchuk
  • 334
  • 6
  • 17

4 Answers4

5

You need to use SelectMany to concatenate result sets.

var items = employees.SelectMany(e => e.Orders.Select(o => new Item(e.ID, o.ID)));
Nick Larsen
  • 18,631
  • 6
  • 67
  • 96
5

For what it's worth, this can be written somewhat more succinctly and clearly in LINQ syntax:

var s = from e in employees
        from o in e.Orders
        select new Item(e.ID, o.ID);
Will Vousden
  • 32,488
  • 9
  • 84
  • 95
  • 1
    While I agree with this, instead of changing the syntax used, I would have argued that `Orders` should have a reference back to `Employee` and there is no need for `Item`. – Nick Larsen Apr 15 '10 at 11:43
  • +1. Note that this syntax is actually translated into SelectMany. Use whatever you find more readable. The generated code is exactly the same. – Niki Apr 15 '10 at 14:57
3

The extension method you're looking for is called "SelectMany": http://msdn.microsoft.com/en-en/library/system.linq.enumerable.selectmany.aspx

Niki
  • 15,662
  • 5
  • 48
  • 74
3

Have a look at Enumerables.SelectMany(), see the example in this Stack Overflow question.

Community
  • 1
  • 1
Paul Ruane
  • 37,459
  • 12
  • 63
  • 82