Reputation: 6061
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
Reputation: 2033
here is the one more
List<Bar> allBars = fooList.SelectMany(foo => foo.Bars).ToList();
Upvotes: 1
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
Reputation: 22717
And another variation:
List<Foo> fooList = GetFooList();
List<Bar> allBars = fooList.SelectMany(x => x.Bars).ToList();
Upvotes: 1
Reputation: 7451
Linq's SelectMany is your friend.
http://msdn.microsoft.com/en-us/library/bb534336.aspx
fooList.SelectMany(f => f.Bars)
Upvotes: 1