通过@DavidMills接受的答案是相当不错,但我认为它可以改进。首先,当框架已经包含一个静态方法Comparer<T>.Create(Comparison<T>)
时,没有必要定义ComparisonComparer<T>
类。这种方法可用于即时创建IComparison
。
此外,它将IList<T>
转换为IList
,这有潜在危险。在我看到的大多数情况下,实现IList
的List<T>
在幕后用于实现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>)
以下类用于实现IList<T>
接口的所有4 List<T>.Sort()
签名:
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