Принятый ответ на @DavidMills является неплохо, но я думаю, что это можно улучшить. Во-первых, нет необходимости определять класс ComparisonComparer<T>
, когда среда уже включает статический метод Comparer<T>.Create(Comparison<T>)
. Этот метод можно использовать для создания IComparison
на лету.
Кроме того, он отличает IList<T>
- IList
, который может быть опасным. В большинстве случаев, которые я видел, List<T>
, который реализует IList
, используется за кулисами для реализации IList<T>
, но это не гарантируется и может привести к хрупкому коду.
Наконец, перегруженный метод List<T>.Sort()
имеет 4 подписи и только 2 из них реализованы.
List<T>.Sort()
List<T>.Sort(Comparison<T>)
List<T>.Sort(IComparer<T>)
List<T>.Sort(Int32, Int32, IComparer<T>)
В приведенной ниже класс реализует все 4 List<T>.Sort()
подписи для интерфейса IList<T>
:
public static class IListExtensions
{
public static void Sort<T>(this IList<T> list)
{
if (list is List<T>)
{
((List<T>)list).Sort();
}
else
{
List<T> copy = new List<T>(list);
copy.Sort();
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparison);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparison);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(comparer);
}
else
{
List<T> copy = new List<T>(list);
copy.Sort(comparer);
Copy(copy, 0, list, 0, list.Count);
}
}
public static void Sort<T>(this IList<T> list, int index, int count,
IComparer<T> comparer)
{
if (list is List<T>)
{
((List<T>)list).Sort(index, count, comparer);
}
else
{
List<T> range = new List<T>(count);
for (int i = 0; i < count; i++)
{
range.Add(list[index + i]);
}
range.Sort(comparer);
Copy(range, 0, list, index, count);
}
}
private static void Copy(IList<T> sourceList, int sourceIndex,
IList<T> destinationList, int destinationIndex, int count)
{
for (int i = 0; i < count; i++)
{
destinationList[destinationIndex + i] = sourceList[sourceIndex + i];
}
}
}
Использование:
class Foo
{
public int Bar;
public Foo(int bar) { this.Bar = bar; }
}
void TestSort()
{
IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };
IList<Foo> foos = new List<Foo>()
{
new Foo(1),
new Foo(4),
new Foo(5),
new Foo(3),
new Foo(2),
};
ints.Sort();
foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));
}
Идея заключается в том, чтобы использовать функциональные возможности базового List<T>
для обработки сортировки, когда это возможно. Опять же, большинство IList<T>
реализаций, которые я видел, используют это. В случае, когда базовая коллекция является другим типом, отмените создание нового экземпляра List<T>
с элементами из списка ввода, используйте его для сортировки, а затем скопируйте результаты обратно в список ввода. Это будет работать, даже если список ввода не реализует интерфейс IList
.
Зачем вам возвращать IList в первую очередь? Из службы WCF? – DaeMoohn 2011-02-18 15:42:20