user2279306
user2279306

Reputation: 41

Confusion around base and derived class

Basic scenario is this:

class MyBase {}
class MyClassA : MyBase {}
class MyClassB : MyBase {}
class MyClassC : MyBase {}

I have an IEnumerable collection of MyBase called source that actually contains a collection of either MyClassA, MyClassB or MyClassC items. Always only of one or the other.

I now want to create a filtered copy of that collection so I perform something similar to this:

IEnumerable<MyBase> filtered = source.Where(s => s.SomeProperty == someVar)

The problem is that if I call the GetType() method on source it says it's a collection of MyClass (A, B or C). However performing GetType() on filtered says that it's a collection of MyBase!

I need it to stay the same!

This is causing me problems as I am binding the filtered collection to a PivotControl which now can't see the properties of MyClass that it needs in the filtered collection.

Because we don't know which of the classes A, B or C is in the collection, I have even tried this:

var entity = source.FirstOrDefault();    
IEnumerable<MyBase> filtered = FilterData(entity);

IEnumerable<MyBase> FilterData<T>(T typeOfObject) where T : MyBase
{
    IEnumerable<T> data = from s in source where s.SomeProperty == someVar select s as T;
    return data;

--OR--

    return source.Where(s => s.SomeProperty == someVar).Cast<T>()'
}

But still it shows in the same way.

Thanks

Upvotes: 0

Views: 89

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

I'm really confused about your question, but think it's all about Cast extension method:

IEnumerable<MyClass> filtered = source.Where(s => s.SomeProperty = someVar).Cast<MyClass>();

Upvotes: 1

Related Questions