ToList()
will not create a CollectionOfA
. You could assign a CollectionOfA
(i.e., the more derived class) to a List<A>
(the less derived class) but not the other way round.
The way to go is to use the Sort
method inherited from List<T>
obj.Sort((a, b) => a.Name.CompareTo(b.Name));
This also has the advantage to not allocate a new collection but to do an in-place sort.
Another option is to add a constructor to your collection class by inheriting the corresponding one form List<T>
:
public class CollectionOfA : List<A>
{
public CollectionOfA()
{
}
public CollectionOfA(IEnumerable<A> collection) : base(collection)
{
}
}
Note that we also must add the default constructor to not break existing code.
We can the use it like this:
obj = new CollectionOfA(obj.OrderBy(x => x.Name).ThenBy(x => x.Id));