2

Consider the following array:

class B { }

class A 
{
    IEnumerable<B> C { get; }
}

IEnumerable<A> array;

I need to end up with one IEnumerable<B>. I'm ending up with IEnumerable<IEnumerable<B>>:

var q = array.Select(a => a.C);

How can I unwind the array?

Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203

2 Answers2

7

You just need to use SelectMany:

IEnumerable<B> allBs = array.SelectMany(a => a.C);
Rawling
  • 49,248
  • 7
  • 89
  • 127
  • Crystal ball analysis at its finest. – Robert Harvey Dec 11 '12 at 15:43
  • @RobertHarvey Not really, I was just privy to the [original question](http://stackoverflow.com/questions/13822750/how-to-use-linq-on-a-multidimensional-array-to-unwind-the-array) where OP generalized this in a way that didn't really generalize, then edited his question to degeneralize it, then had his edit rolled back because people had answered the original. – Rawling Dec 11 '12 at 15:45
3

Use SelectMany:

var q = array.SelectMany(a => a.C);

This will give you an IEnumerable<B> containing the flattened contents of the C property of each item in array.

Jon B
  • 51,025
  • 31
  • 133
  • 161