How to sort a list of numbers by first digit in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> list = new List<int>();

            list.Add(5);
            list.Add(0);
            list.Add(10);
            list.Add(20);
            list.Add(100);
            list.Add(90);
            list.Add(30);

            list.Sort((a, b) => (a.ToString()[0].CompareTo(b.ToString()[0])));

            foreach (int n in list)
                Console.WriteLine(n);
        }
    }
}


/*
run:
    
0
10
100
20
30
5
90

*/

 



answered Feb 13, 2017 by avibootz
...