Kees C. Bakker
Kees C. Bakker

Reputation: 33371

How to use LINQ to get a single IENumerable<X> from a property of an IEnumerable<T>?

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?

Upvotes: 2

Views: 335

Answers (2)

user27414
user27414

Reputation:

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.

Upvotes: 3

Rawling
Rawling

Reputation: 50104

You just need to use SelectMany:

IEnumerable<B> allBs = array.SelectMany(a => a.C);

Upvotes: 7

Related Questions