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.
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:
How can I sort a generic Collection<T>
?
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(); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With