实现List<T>,为什么在LINQ之后不会转回MyList? (无法转换 'WhereListIterator`1 类型的对象)

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

可能是我错过了一些愚蠢的东西,但到目前为止搜索还没有发现任何结果。 我已经在我的类上实现了 List,当使用 MyList.Where() 函数时,它不会转换回 MyList 对象?

public class VideoList : List<Video>
{
    public VideoList GetVideos(bool onlyShorts)
        => (VideoList)this.Where(x => x.IsShort.Equals(onlyShorts)).ToList();
}

抛出错误

Unable to cast object of type 'WhereListIterator
1[视频]' 输入“视频列表”。`

按照网上的建议尝试了一些不同类型的铸造,但到目前为止我还没有通过这个错误。 也尝试过this,但同样的问题。 可能有一些语义? 有没有办法解决此错误,而无需 foreach 在 linq 语句后重新创建列表?

c# list linq
1个回答
0
投票
this.Where(x => x.IsShort.Equals(onlyShorts)).ToList()

产生“List

如果您仍然希望 GetVideos 返回 VideoList,您需要拥有并使用适当的构造函数(作为可能的解决方案):

public VideoList(List<Video>) { ... }

public VideoList GetVideos(bool onlyShorts)
    => new VideoList(this.Where(x => x.IsShort.Equals(onlyShorts)).ToList());
© www.soinside.com 2019 - 2024. All rights reserved.