【问题标题】:Public property List needs to Concat 2 types with inheritance公共属性 List 需要 Concat 2 类型与继承
【发布时间】:2010-03-22 16:20:45
【问题描述】:

我有 2 个列表:一个 A 类型,一个 Aa 类型。 Aa 类型继承自 A 类型。 所以:

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

我可以以某种方式使用 Concat 代替 foreach 循环吗?即

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

其次,属性的set部分怎么做?

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

【问题讨论】:

  • @Obalix:从最初来看,我不能 100% 确定这些是通用列表,而不是 System.Collections.List...
  • @Reed Copsey:刚刚进行了格式化... :-) ... 根据 Bernard 的 OP,列表被定义为 List 和 List
  • 啊,好吧 - 从原始文本中看不出来,它有:“List listA = new List();”等...暗示非通用用法。

标签: c# linq list ienumerable


【解决方案1】:

如果这些是通用列表,如下所示:

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

你应该可以做到:

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

Enumerable.Cast 的调用将允许您将List&lt;Aa&gt; 转换为IEnumerable&lt;A&gt;(因为Aa 是A 的子类),这将使Concat 工作。然后,您可以通过调用 ToList() 将其转换回 List&lt;A&gt;

至于属性设置器 - 我不建议让该属性包含属性设置器。这将以非常非标准的方式表现。相反,创建一个自定义方法来处理设置列表很可能是一个更好的主意。

如果您要传入一个包含 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 设置这些数组更有效,因为您需要进行一些奇怪的过滤。

【讨论】:

    【解决方案2】:

    此外,由于协方差,它可以在 .net 4.0 中运行而无需强制转换

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 2011-01-05
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多