How to sort elements of array list in C#

后端 未结 9 1124
梦如初夏
梦如初夏 2021-02-14 23:42

I have an ArrayList that contains,

[0] = \"1\"
[1] = \"10\"
[2] = \"2\"
[3] = \"15\"
[4] = \"17\"
[5] = \"5\"
[6] = \"6\"
[7] = \"27\"
[8] = \"8\"
[9] = \"9\"
         


        
9条回答
  •  广开言路
    2021-02-15 00:11

    There are numerous sort methods in the framework including ArrayList.Sort. The problem is that they are all going to sort alphabetically and not numerically. You'll need to write a custom sorter that understands numeric sorts.

    Try the following (some argument checking left out for brevity)

    public class NumericComparer : IComparer {
      public int Compare(object x, object y) {
        string left = (string)x; 
        string right = (string)y;
        int max = Math.Min(left.Length, right.Length);
        for ( int i = 0; i < max; i++ ) {
          if ( left[i] != right[i] ) { 
            return left[i] - right[i];
          }
        }
        return left.Length - right.Length;
      }
    }
    
    list.Sort(new NumericComparer());
    

提交回复
热议问题