How to sort a list of strings by first letter 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<string> list = new List<string>();

            list.Add("c#");
            list.Add("java");
            list.Add("python");
            list.Add("c++");
            list.Add("c");
            list.Add("php");

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

            foreach (string s in list)
                Console.WriteLine(s);
        }
    }
}


/*
run:
    
c#
c++
c
java
python
php

*/

 



answered Feb 13, 2017 by avibootz
...