Arseni Mourzenko
Arseni Mourzenko

Reputation: 52371

Treat multiple IEnumerable objects as a single IEnumerable

My question seems to be something easy, but I can't figure it out.

Let's say I have a "root" IEnumerable of objects. Each object has IEnumerable of strings. How can I obtain a single IEnumerable of those strings?

A possible solution is to do:

public IEnumerable<string> DoExample()
{
    foreach (var c in rootSetOfObjects)
    {
        foreach (var n in c.childSetOfStrings)
        {
            yield return n;
        }
    }
}

But maybe there is a magic solution with Linq?

Upvotes: 0

Views: 325

Answers (2)

Sonic Soul
Sonic Soul

Reputation: 24979

there is SelectMany in Linq that should work for you: http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectManyCompoundfrom1

it definitely works on your collection and compound collections

Upvotes: 1

Bryan Watts
Bryan Watts

Reputation: 45475

rootSetOfObjects.SelectMany(o => o.childSetOfStrings)

Upvotes: 5

Related Questions