Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach over a collection of IEnumerables

I have 3 (Edit) mutually exclusive IEnumerables that I want to iterate over. I want to do something like this:

IEnumerable<Car> redCars = GetRedCars();
IEnumerable<Car> greenCars = GetGreenCars();
IEnumerable<Car> blueCars = GetBlueCars();

foreach(Car c in (redCars + greenCars + blueCars)) {
    c.DoSomething();
}

...

The best way I can think of is:

...
List<Car> allCars = new List();
allCars.AddRange(redCars);
allCars.AddRange(greenCars);
allCars.AddRange(blueCars);
foreach(car in allCars) {
    ...
}
...

Is there a more concise way to do this? Seems like combinding IEnumberables should be trivial.

like image 881
sdr Avatar asked Mar 22 '10 20:03

sdr


1 Answers

With LINQ:

foreach(car in redCars.Concat(greenCars).Concat(blueCars)) {
    //...
}

For info, the difference here between Union and Concat is that Union will do extra work to guarantee uniqueness; so if you don't expect duplicates (or alternatively: don't mind them) then Concat is faster.

like image 95
Marc Gravell Avatar answered Oct 25 '22 02:10

Marc Gravell