我有一个自定义集合如下:(我不会显示该类的所有代码)
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());
}
为什么我不能使用 test1 和 test2
中的代码答案 0 :(得分:5)
我猜你错误地认为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());