-1

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!

Tom
  • 3,899
  • 22
  • 78
  • 137

2 Answers2

2

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>?.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 1
    Try reading [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask). Read your question in the mindset of someone who doesn't know what you're doing. That will really help you reword the question so it's clear from the beginning. – CodeCaster Jun 04 '15 at 09:13
0

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);
Enigmativity
  • 113,464
  • 11
  • 89
  • 172