How to sort a list of strings by length 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>
            {
                "python",
                "c#",
                "c",
                "c++",
                "java"
            };

            IEnumerable<string> ie = SortStringByLength(list);

            foreach (string s in ie)
                Console.WriteLine(s);
        }
        static IEnumerable<string> SortStringByLength(IEnumerable<string> ie)
        {
            var sorted = from s in ie
                         orderby s.Length ascending
                         select s;

            return sorted;
        }
    }
}


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

*/

 



answered Mar 13, 2017 by avibootz
edited Mar 13, 2017 by avibootz
...