How to sort an array of numeric strings in ascending order with C#

1 Answer

0 votes
using System;

class Program
{
    public static int Compare(string string1, string string2) {
        if (string1.Length == string2.Length) {
            return Convert.ToInt32(string1) - Convert.ToInt32(string2);
        }
        else {
            return string1.Length - string2.Length;
        }
      }
 
    static void Main() {
        string[] arr = { "7", "0", "55", "8", "9", "6" };
 
        Array.Sort<string>(arr, delegate(string x, string y) { return Compare(x, y); });
 
        for (int i = 0; i < arr.Length; i++) {
            Console.Write(arr[i] + " ");
        }
    }
}



/*
run:

0 6 7 8 9 55 

*/

 



answered Sep 2, 2022 by avibootz
edited Sep 3, 2022 by avibootz

Related questions

...