Ascii Sort on a Collection in C#

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 578
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

var lstString = new List<string>()
{
"14",
"12",
"27 Oct contri head",
"563395",
"565302",
"8th Dec -12th Dec",
"sample string 4",
"add contribution head",
"Navarathri",
"Nov 5 Head Sumeru travel",
"Product A",
"WCF Contribution",
"test WCF",
""
};


lstString.Sort(); //default sort

lstString =
lstString
.Where(w => w.ToCharArray().Length > 0) //sort those records whose length > 0 e.g. "" will be ignored
.Select(s => new { OriginalString = s, GetAsciiofFirstChar = (int)s.ToCharArray().Take(1).Single() }) //find the ascii of first charecters
.OrderBy(o => o.GetAsciiofFirstChar) //sort the records by ASCII character
.Select(s => s.OriginalString) //Project the sorted original string
.Union(lstString.Where(s => s.ToCharArray().Length == 0)) //Add those records to the sorted result whose length = 0 e.g. include ""
.ToList(); //Convert the IEnumerable to List

}
}
}

Comments or Responses

Login to post response