To sort in-place you would essentially see these two approaches:
IList<T> list = .... // your ilist
var sorted = list.ToArray();
Array.Sort(sorted);
for (int i = 0; i < list.Count; i++)
{
list[i] = sorted[i];
}
and
IList<T> list = .... // your ilist
ArrayList.Adapter((IList)list).Sort();
The second one might look simpler but won't be great for value type collections since it incur boxing penalties. Furthermore there is no guarantee your IList<T>
will be implementing IList
. First one is better IMO.
You can also use the first approach to sort an ICollection<T>
in-place but it is questionable if you should expose such a functionality since ICollection<T>
contract doesn't guarantee an order (think hash structures). Anyway to show you code example:
ICollection<T> collection = .... // your icollection
var sorted = collection.ToArray();
Array.Sort(sorted);
collection.Clear();
foreach (var i in sorted)
{
collection.Add(i);
}
A note on sort stability, .NET's Array/List sorting algorithms are unstable. For a stable sort you will have to use:
IList<T> list = .... // your ilist
var sorted = list.OrderBy(i => i).ToArray();
for (int i = 0; i < list.Count; i++)
{
list[i] = sorted[i];
}
This can't be as fast as unstable sorts.
Finally, for a complete answer, perhaps a composite approach taken by watbywbarif is better:
public static void Sort<T>(this IList<T> list, IComparer<T> comparer, bool stable)
{
if (stable)
{
list.StableSort(comparer);
}
else
{
list.UnstableSort(comparer);
}
}
static void StableSort<T>(this IList<T> list, IComparer<T> comparer)
{
list.OrderBy(x => x, comparer).CopyTo(list);
}
static void UnstableSort<T>(this IList<T> list, IComparer<T> comparer)
{
switch (list)
{
case List<T> l:
l.Sort(comparer);
break;
case T[] a:
Array.Sort(a, comparer);
break;
default:
T[] sortable = list.ToArray();
sortable.UnstableSort(comparer);
sortable.CopyTo(list);
break;
}
}
static void CopyTo<T>(this IEnumerable<T> source, IList<T> target)
{
int i = 0;
foreach (T item in source)
{
target[i++] = item;
}
}
That's as far as built-in approaches go. For faster implemenation you will have to roll out your own, see: https://stackoverflow.com/a/19167475
myobj
always aList
? If so, you can cast it to aList
and run itsSort
function. – Circumrotate