Combine contents of list member of object collection into single list with linq

Is it possible to replace the foreach loop below with linq?

public class Foo
{
    List<Bar> Bars {get; set;}
}

List<Foo> fooList = GetFooList();
List<Bar> allBars = new List<Bar>();

foreach (Foo foo in fooList)
{
    allBars.AddRange(foo.Bars);
}

The closest I've gotten is:

var temp = fooList.Select(foo => foo.Bars).ToList();

which gives a List<List<Bar>>.

Upvotes: 1

Views: 156

Answers (4)

dipak
dipak

Reputation: 2033

here is the one more

   List<Bar> allBars = fooList.SelectMany(foo => foo.Bars).ToList();

Upvotes: 1

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38508

You can use SelectMany() on foo.Bars

allBars.AddRange(fooList.SelectMany(foo => foo.Bars));

If allBars variable does not contain anything before AddRange(), you could skip the object creation:

List<Bar> allBars = fooList.SelectMany(foo => foo.Bars).ToList();

And if you are not going to use fooList somewhere else, you could just write:

List<Bar> allBars = GetFooList().SelectMany(foo => foo.Bars).ToList();

Upvotes: 2

John Fisher
John Fisher

Reputation: 22717

And another variation:

List<Foo> fooList = GetFooList();
List<Bar> allBars = fooList.SelectMany(x => x.Bars).ToList();

Upvotes: 1

Andrew Hanlon
Andrew Hanlon

Reputation: 7451

Linq's SelectMany is your friend.

http://msdn.microsoft.com/en-us/library/bb534336.aspx

fooList.SelectMany(f => f.Bars)

Upvotes: 1

Related Questions