按降序C#对字符串列表进行自然排序 [英] Natural Sorting of list of string in descending order C#
问题描述
I would like to ask how to sort a List<string>
in descending order using the Natural Sort Comparer library.
我想问一下您是否有人使用过这个库
https://www.codeproject.com/Articles/22517/Natural-Sort-比较器
对List<string>
进行排序?
I would like to ask if you someone have use this library
https://www.codeproject.com/Articles/22517/Natural-Sort-Comparer
to sort a List<string>
?
这是升序的代码段
public List<string> contents = new List<string>{ "a,b,c,d,e,f" };
public void sorting()
{
using (NaturalSortComparer comparer = new NaturalSortComparer())
{
contents.Sort(comparer);
}
}
我可以使其按升序进行排序,但不能按降序进行排序.
I'm able to make it work to sort as ascending, but not descending.
有什么想法吗?
推荐答案
让我们实现一个简单的扩展方法 :
Let's implement a simple extension method:
public static partial class ComparerExtensions {
public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
if (null == comparer)
throw new ArgumentNullException(nameof(comparer));
return Comparer<T>.Create((left, right) => comparer.Compare(right, left));
}
}
然后,您可以反转任意一个任何比较器(ICompare<T>
):
Then you can reverse any comparer (ICompare<T>
) you like:
MyList.Sort(YourCustomComparer.Reverse());
在您的情况下(比较器实现IDisposable
有点奇怪的实现):
In your case (a bit strange implmentation with comparer implementing IDisposable
):
using (var naturalComparer = new NaturalComparer()) {
contents.Sort(naturalComparer.Reverse());
}
对于 C#4.0 或更早的版本(不具有Comparer<T>.Create
),我们可以实现以下扩展方法:
In case of C# 4.0 or earlier version (which doesn't have Comparer<T>.Create
) we can implement the extension method like this:
public static partial class ComparerExtensions {
private sealed class ReversedComparer<T> : IComparer<T> {
private readonly IComparer<T> m_Comparer;
public ReversedComparer(IComparer<T> comparer) {
m_Comparer = comparer;
}
public int Compare(T x, T y) {
return m_Comparer.Compare(y, x);
}
}
public static IComparer<T> Reverse<T>(this IComparer<T> comparer) {
if (null == comparer)
throw new ArgumentNullException(nameof(comparer));
return new ReversedComparer<T>(comparer);
}
}
这篇关于按降序C#对字符串列表进行自然排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!