views:

32

answers:

2

I have 2 lists: one of type A and one of type Aa. type Aa is inherited from type A. So:

List<A> listA = new List<A>();
List<Aa> listAa = new List<Aa>();

with

class Aa : A

I have:

public property Lists<A>
{
  get
   {
    List<A> newList = new List<A>();
    //return concat of both lists
    foreach(List l in listA)
    {
      newList.Add(l);
    }
    foreach(List l in listAa)
    {
      newList.Add(l);
    }
}

Can I somehow use Concat instead of the foreach loop? i.e.

get
{
  return listA.Concat(listAa);
} // this doesn't work

And secondly, how do I do the set part of the property?

set
{
  //figure out the type of variable value and put into appropriate list?
}
+2  A: 

If these are generic lists, like so:

List<A> listA;
List<Aa> listAa;

You should be able to do:

public IList<A> Lists
{
    get 
    {
        return listA.Concat(listB.Cast<A>()).ToList();
    }
}

The call to Enumerable.Cast will allow you to convert the List<Aa> into an IEnumerable<A> (since Aa is a subclass of A), which will make Concat work. You can then convert this back into a List<A> by calling ToList().

As for the property setter - I would not recommend making this property contain a property setter. This is going to behave in a VERY non-standard manner. Instead, it would most likely be a much better idea to make a custom method for handling setting the lists.

If you're going to pass in a single list, containing Aa and A classes, you could use something like:

public void SetLists(IEnumerable<A> newElements)
{
    this.listA.Clear();
    this.listAa.Clear();
    foreach(A aElem in newElements)
    {
        Aa aaElem = aElem as Aa;
        if (aaElem != null)
            this.listAa.Add(aaElem);
        else
            this.listA.Add(aElem);
    }
}

In this case, doing the loop will actually be more efficient than trying to use LINQ for setting these arrays, since you're going to have some odd filtering required.

Reed Copsey
A: 

also, it will work in .net 4.0 without a cast because of covariance

Nagg