使用 as 投射自定义集合失败

Casting a custom collection using as fails

我有一个自定义 Collection 如下:(我不会显示 class 的所有代码)

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

我只想要集合中 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());
}

为什么我不能使用test1test2

中的代码

我猜你误以为 MyCollection.Where 的结果是 MyCollection。不是,是IEnumerable<T>,其中T是物品类型,在本例中是MyOBject

此代码应该有效:

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

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

MyCollection coll = new MyCollection(test1.ToArray());