无法将 List<T> 转换为从 List<T>

问题描述 投票:0回答:1

我从

List<T>
派生了一个类“ListOfT”,以便有一个地方放置对 T 列表进行操作的函数。

我有一个迭代列表的函数,并且应该使用 Linq 返回 T 的子列表:

public class ListOfT : List<T> 
{
  //no explicit constructor
  //other functions to work on this list of T's ...

  public ListOfT GenerateSubList()
  {
    return this.Where(t => t.SomeCriteria).ToList(); // <- compiler will complain

    return (ListOfT) this.Where(t => t.SomeCriteria).ToList(); // <- compiler is ok, but I get a runtime error
  }
}

编译器现在抱怨它无法将

List<T>
转换为 ListOfT。显然,对“ToList()”的调用将生成一个新的
List<T>
,但我想要创建 ListOfT 实例的东西。

我尝试了显式强制转换(这将使编译器平静下来),但这会导致运行时错误。

是否有一种优雅的方法来执行此转换(或替换 ToList() 调用)?

c# list linq
1个回答
0
投票

List<T>
中有一个构造函数,它接受
IEnumerable<T>
。您可以从您的子类中调用它:

public class MyList<T> : List<T>
{
    public MyList()
    {
    }

    private MyList(IEnumerable<T> items)
    : base(items)
    {
    }

    public MyList<T> GenerateSubList()
    {
        return new MyList<T>(this.Where(t => t.SomeCriteria));
    }
}

当然,如果您想在类外部使用构造函数,也可以将其公开。

在线演示:https://dotnetfiddle.net/RxBMr0

© www.soinside.com 2019 - 2024. All rights reserved.