Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c#, Is it possible to loop through multiple collections of the same base type?

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.

like image 393
Blake Avatar asked Oct 22 '25 06:10

Blake


1 Answers

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;
    }
like image 178
Magnus Avatar answered Oct 23 '25 22:10

Magnus