Suppose classes 'Apple', 'Banana' and 'Orange' all inherit from 'Fruit'.
Now suppose we have member variable lists -
List<Apple> mApples;
List<Banana> mBananas;
List<Orange> mOranges;
Can we form a loop that does something equivalent to the following?
foreach( Fruit fruit in mApples, mBananas, mOranges )
{
fruit.Slice();
}
I'm using .net 2.0.
You would have to concatenate the lists
foreach(Fruit fruit in mApples.Cast<Fruit>()
.Concat(mBananas.Cast<Fruit>())
.Concat(mOranges.Cast<Fruit>()))
{
fruit.Slice();
}
Edit
This would be a possible 2.0 solution
foreach(Fruit fruit in Concat<Fruit>(mApples, mBananas, mOranges))
{
fruit.Slice();
}
public static IEnumerable<T> Concat<T>(params IEnumerable<T>[] arr)
{
foreach (IEnumerable col in arr)
foreach (T item in col)
yield return item;
}
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