views:

81

answers:

4

Hello,

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

+3  A: 

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

nikie
+5  A: 

You need to use SelectMany to concatenate result sets.

var items = employees.SelectMany(e => e.Orders.Select(o => new Item(e.ID, o.ID)));
NickLarsen
+2  A: 

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

Paul Ruane
+5  A: 

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
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`.
NickLarsen
+1. Note that this syntax is actually translated into SelectMany. Use whatever you find more readable. The generated code is exactly the same.
nikie