Natural Sorting of list of string in descending order C#

别等时光非礼了梦想. 提交于 2019-12-11 11:55:22

问题


I would like to ask how to sort a List<string> in descending order using the Natural Sort Comparer library.

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>?

This is the code snippets for ascending

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.

Any ideas?


回答1:


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));
    }
  }

Then you can reverse any comparer (ICompare<T>) you like:

 MyList.Sort(YourCustomComparer.Reverse());

In your case (a bit strange implmentation with comparer implementing IDisposable):

 using (var naturalComparer = new NaturalComparer()) {
   contents.Sort(naturalComparer.Reverse()); 
 }

Edit: 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);
    }
  }



回答2:


You have two options:

  1. Horrible, never do this: use the ascending order and then simply call Reverse() method (I'm only listing this option as a warning because, believe it or not, I've seen it more than once in production code).
  2. The good way: Implement an IComparer<string> that simply returns the negative of the "ascending" comparer (or switches the argument order) and pass it into your sorting method.

But nº2 is already built in the framework for you; its the extension method OrderByDescending:

var ss = new[] {"a1", "a03", ... }
var descending = ss.OrderByDescending(
    s => s,
    new NaturalComparer());

UPDATE: Your updated question seems to imply you want to use List.Sort. In that case the way to go is #2, OrderBy will not sort in place.



来源:https://stackoverflow.com/questions/53611279/natural-sorting-of-list-of-string-in-descending-order-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!