Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a Collection<T> in-place?

Tags:

c#

.net

sorting

I have a generic collection:

public Items : Collection<Object>
{
   protected override void InsertItem(int index, Object item)
   {
      base.InsertItem(index, item);
      ...
   }

   protected override void RemoveItem(int index)
   {
      base.RemoveItem(index);
      ...
   }

   protected override void SetItem(int index, Object item)
   {
      base.SetItem(index, item);
      ...
   }

   protected override void ClearItems()
   {
      base.ClearItems();
      ...
   }

Now I need a way to sort this collection in-place.

Bonus Chatter

I tried converting my class to use List<T> rather than Collection<T> (since Collection<T> doesn't support the concept of an order). That then allowed calling the Sort method:

this.Items.Sort(SortCompareCallback);

protected virtual int SortCompareCallback(Object x, Object y)
{
   return OnCompareItems(new SortCompareEventArgs(x, y, this.sortColumnIndex, direction));
}

But then I lose the virtual methods when the list is modified.

I thought about using Linq, but the problem with that is:

  • I don't know how to call a callback from a Linq expression
  • Linq doesn't sort a collection, it can only return a new one

How can I sort a generic Collection<T>?

like image 746
Ian Boyd Avatar asked Feb 16 '12 21:02

Ian Boyd


1 Answers

If you don't need to have the virtual overrides called during the sorting, you should be able to do something like this:

class SortableCollection<T> : Collection<T>
{
    private readonly List<T> _list;

    public SortableCollection() : this(new List<T>()) {}
    public SortableCollection(List<T> list) : base(list)
    {
        _list = list;
    }
    public void Sort() { _list.Sort(); }
}

Or this:

class SortableCollection<T> : Collection<T>
{
    public SortableCollection() : this(new List<T>()) {}
    public SortableCollection(List<T> list) : base(list) {}
    public void Sort() { ((List<T>)Items).Sort(); }
}
like image 141
phoog Avatar answered Oct 06 '22 02:10

phoog