Linq order by with cast as
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
s开发者_开发知识库o 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 testFoo
can only be a Foo
or an object derived from Foo
(List<Bar>
is a base class of Foo
)
You can, however, do something like this:
public class Foo : List<Bar>
{
public Foo()
{}
public Foo(IEnumerable<Bar> collection)
: base(collection)
{}
}
And in your code later on:
Foo testFoo = new Foo();
testFoo = new Foo(testFoo.OrderBy(b => b.BarDate));
The LINQ expression will return an IEnumerable<Bar>
, so is compatible with one of the constructors of List<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 Foo
that happens to be referenced as a List<Bar>
then you can cast it. e.g.
Foo myFoo = new Foo();
List<Bar> myList = myFoo;
Foo sameFoo = (Foo)myList;
All three references (myFoo
, myList
, and sameFoo
) all reference the exact same Foo
instance and casting will work. However, if this is the scenario:
List<Bar> actualList = new List<Bar>();
Foo listedFoo = (Foo)actualList;
Then the cast will fail because actualList
isn't a Foo
or derivative of Foo
.
ToList()
returns a new List<Bar>
. There is not way of getting a Foo
object back.
That is one of the reasons you should not inherit from List
.
精彩评论