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>>.
You can use SelectMany() on foo.Bars
If allBars variable does not contain anything before AddRange(), you could skip the object creation:
And if you are not going to use fooList somewhere else, you could just write: