Search code examples
c#castingicollection

Casting a custom collection using as fails


I have a custom Collection as follows: (I wont show all the code of the class)

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

I only want entries in the collection where SomeValue=false and I am trying to work out why I cannot use the as operator as follows:

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());
}

Why can I not use the code in test1 and test2


Solution

  • I guess you are mistakenly thinking the result of MyCollection.Where is an MyCollection. It is not, it is IEnumerable<T>, where T is the item type, which is MyOBject in this case.

    This code should work:

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

    You might want to feed that back to your MyCollection constructor:

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