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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With