I have a class derived from List:
public class B : List<A>
{
}
How can I call List methods on B? E.g.
var test = new B();
test = test.OrderBy(s=>s.SomeProperty);
Thanks very much!
I have a class derived from List:
public class B : List<A>
{
}
How can I call List methods on B? E.g.
var test = new B();
test = test.OrderBy(s=>s.SomeProperty);
Thanks very much!
According to your comment, you want to assign the result of IEnumerable<T>.OrderBy()
to a B
variable.
You can't do that, as there is no implicit conversion from IEnumerable<T>
(or rather IOrderedEnumerable<T>
to B
.
Just as you can't do:
List<string> stringList = new List<string> { "foo", "bar" };
stringList = stringList.OrderBy(s => s);
You can't do that with your own type. For the above code the fix is simple:
stringList = stringList.OrderBy(s => s).ToList();
You can for example implement a constructor, extension method or implicit or explicit conversion to solve this:
public class B : List<A>
{
public B(IEnumerable<A> items)
{
base.AddRange(items);
}
}
Then assign a new instance:
test = new B(test.OrderBy(s=>s.SomeProperty));
Anyway you shouldn't want to inherit from List<T>
, read Why not inherit from List<T>?.
If you are asking how to assign test.OrderBy(...)
to test
then you need to do it like this:
IEnumerable<A> test = new B();
test = test.OrderBy(s => s.SomeProperty);
But doing that would prevent you adding anything to test
.
You'd need to do it this way:
B b = new B();
/* add items to `b` here */
IEnumerable<A> test = b;
test = test.OrderBy(s => s.SomeProperty);