2010-03-22 77 views
3

我有2个列表:A类型和Aa类型之一。 AA型是由A型 所以继承:公共属性列表需要Concat 2继承类型

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

class Aa : A 

我:

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); 
    } 
} 

我可以以某种方式使用,而不是foreach循环的毗连?即

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

其次,我该如何做属性的设置部分?

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

@Obalix:从原来的,我不是100%肯定这些都是通用的清单,而不是System.Collections.List .. – 2010-03-22 16:26:24

+0

@Reed Copsey:刚做格式化...... :-) ......根据Bernard的OP,列表被定义为列表和列表。 – AxelEckenberger 2010-03-22 16:33:03

+0

啊,好吧 - 从原始文本中并不明显,它包含:“List listA = new List();”等等,表明非泛型用法。 – 2010-03-22 16:50:53

回答

2

如果这些是通用的列表,像这样:

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

你应该能够做到:

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

Enumerable.Cast电话将允许你在List<Aa>转换成IEnumerable<A>(因为Aa是A的一个子类),这将使Concat工作。您可以通过拨打ToList()将其转换回List<A>

至于属性setter - 我不会建议使这个属性包含一个属性setter。这将以非常不规范的方式行事。相反,使用自定义方法处理设置列表最有可能是一个更好的主意。

如果你想在一个列表来传递,含AaA类,你可以使用类似:

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); 
    } 
} 

在这种情况下,做循环实际上是比试图更有效使用LINQ来设置这些数组,因为你将需要一些奇怪的过滤。

0

也,它会在.NET 4.0中工作,没有一个造型,因为协方差