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>?
If you don’t need to have the virtual overrides called during the sorting, you should be able to do something like this:
Or this: