使用as铸造自定义集合失败

Har*_*Boy 0 c# casting icollection

我有一个自定义集合如下:(我不会显示该类的所有代码)

public class MyCollection : IList<MyOBject>, ICollection<MyOBject>, IEnumerable<MyOBject>, IEnumerable, IDisposable
{
    //Constructor
    public MyCollection (MyOBject[] shellArray);
    // blah blah
}
Run Code Online (Sandbox Code Playgroud)

我只想要集合中SomeValue = false的条目,我想弄清楚为什么我不能使用as运算符,如下所示:

MyCollection SortCollection(MyCollection collection)
{
    MyCollection test1 = collection.Where(x => (bool)x["SomeValue"].Equals(false)) as MyCollection ; //test1 = null

    var test2 = collection.Where(x => (bool)x["SomeValue"].Equals(false)) as MyCollection ;          //test2 = null

    var test3 = collection.Where(x => (bool)x["SomeValue"].Equals(false)); //test3 is non null and can be used
    return new MyCollection (test3.ToArray());
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能在test1test2中使用代码

Pat*_*man 5

我猜你错误地认为结果MyCollection.Where是一个MyCollection.它不是,在这种情况下,项目类型IEnumerable<T>在哪里.TMyOBject

这段代码应该有效:

IEnumerable<MyOBject> test1 = collection.Where(x => (bool)x["SomeValue"].Equals(false));
Run Code Online (Sandbox Code Playgroud)

您可能希望将其反馈给MyCollection构造函数:

MyCollection coll = new MyCollection(test1.ToArray());
Run Code Online (Sandbox Code Playgroud)