So I have an object the inherits a list.
public class Foo: List<Bar>
And I want to reorder it by BarDate which is a property on Bar
For example
Foo testFoo = GetFoo();
testFoo = testFoo.OrderBy(b => b.BarDate).ToList();
but testFoo is of type Foo not List so how could I do the cast?
Thanks
You can’t do that. You are setting a reference to a derived class an instance of its base which won’t work.
The reference
testFoocan only be aFooor an object derived fromFoo(List<Bar>is a base class ofFoo)You can, however, do something like this:
And in your code later on:
The LINQ expression will return an
IEnumerable<Bar>, so is compatible with one of the constructors ofList<T>Incidentally, the reason the compiler error message says “An explicit conversion exists (are you missing a cast?)” is because if you have an object that really is a
Foothat happens to be referenced as aList<Bar>then you can cast it. e.g.All three references (
myFoo,myList, andsameFoo) all reference the exact sameFooinstance and casting will work. However, if this is the scenario:Then the cast will fail because
actualListisn’t aFooor derivative ofFoo.