要进行原地排序,您基本上会看到这两种方法:
IList<T> list = ....
var sorted = list.ToArray();
Array.Sort(sorted);
for (int i = 0; i < list.Count; i++)
{
list[i] = sorted[i];
}
并且
IList<T> list = .... // your ilist
ArrayList.Adapter((IList)list).Sort()
第二个可能看起来更简单,但对于值类型集合来说并不是很好,因为它会产生装箱开销。此外,不能保证您的IList将实现IList接口。在我看来,第一个更好。
您也可以使用第一种方法来原地排序 ICollection<T>
,但是是否应该公开这样的功能还有疑问,因为 ICollection<T>
的契约并不保证顺序(考虑哈希结构)。无论如何,以下是代码示例:
ICollection<T> collection = ....
var sorted = collection.ToArray();
Array.Sort(sorted);
collection.Clear();
foreach (var i in sorted)
{
collection.Add(i);
}
关于排序稳定性的说明,.NET的数组/列表排序算法是不稳定的。
如果要进行稳定排序,您必须使用:
IList<T> list = ....
var sorted = list.OrderBy(i => i).ToArray();
for (int i = 0; i < list.Count; i++)
{
list[i] = sorted[i];
}
这不能像不稳定排序那样快。
最后,为了得到一个完整的答案,也许采用watbywbarif提出的综合方法更好:
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;
}
}
这就是内置方法所能达到的限度。为了更快的实现,你需要自己动手编写代码,参考:https://stackoverflow.com/a/19167475
myobj
一直都是List
吗?如果是,你可以将其转换为List
并运行它的Sort
函数。 - Gabe