lundi 31 août 2015

Create an IEnumerable

I have a class that is composed of many collections like so:

public virtual ICollection<C> CStuff { get; set; }
public virtual ICollection<D> DStuff { get; set; }
public virtual ICollection<E> EStuff { get; set; }

Each of the types implement a common interface.

public class C : IStuff {}
public class D : IStuff {}
public class E : IStuff {}

I would like to create a collection of all the IStuff in my class, like so:

IEnumerable<IEnumerable<IStuff>> AllStuffCollections 
{
    get { /* how??? */ }
}

public IEnumerable<IStuff> AllStuff 
{ 
   get 
   { 
       foreach (IEnumerable<IStuff> stuffCollection in AllStuffCollections) 
       {
           foreach (IStuff stuff in stuffCollection) 
           {
               yield return stuff;
           }
       }
   }
}

Is there any way to accomplish this (reflection's OK) without adding each collection explicitly? As in, I don't want to do this:

IEnumerable<IEnumerable<IStuff>> AllStuffCollections 
{
    get 
    { 
        return new List<IEnumerable<IStuff>>() 
        { 
            CStuff.Cast<IStuff>, 
            DStuff.Cast<IStuff>,
            EStuff.Cast<IStuff>
        }
    }
}

Ultimately this class will be adding more collections of IStuff over time and I'm afraid I'll forget to include them in AllStuffCollections when it changes.

Additionally the collections themselves are lazy (EF-populated) so I don't want to do anything that would force an immediate "query all the things" to happen.





Aucun commentaire:

Enregistrer un commentaire