Karthick Karthi Karthick Karthi - 3 months ago 32
ASP.NET (C#) Question

How to sort an alphanumeric list by alphabet order

I am trying to sort an string list by country name which contains four digit number in front of each string elements. But, I actually get sorted by the numbers in front of each string instead of getting sorted by country name. Can anyone help me how to ignore the numbers in from of string while sorting. Thanks.

List<string> lst = new List<string>();
lst.Add("0003 India");
lst.Add("0005 America");
lst.Add("0004 Japan");
lst.Add("0001 Sweden");
lst.Add("0002 Germany");

lst.Sort();

lstSearchResult.DataSource = lst;
lstSearchResult.DataBind();


Output I am getting :

0001 Sweden
0002 Germany
0003 India
0004 Japan
0005 America


I actually wanted output

0005 America
0002 Germany
0003 India
0004 Japan
0001 Sweden

Answer

The reason lst.Sort() isn't working is because it is using the default Comparison of string - which takes the entire string to do the sorting. What you want to do is sort only by the part of the string after the space. To do so:

You can use Linq's .OrderBy method on the splitted second part of the string:

List<string> lst = new List<string>();

lst.Add("0003 India");
lst.Add("0005 America");
lst.Add("0004 Japan");
lst.Add("0001 Sweden");
lst.Add("0002 Germany");

lst = lst.OrderBy(item => item.Split(' ').ElementAtOrDefault(1)).ToList();

// Or if always by the string from position 5 onward then:
lst = lst.OrderBy(p => p.Substring(5)).ToList();

lstSearchResult.DataSource = lst;
lstSearchResult.DataBind();
Comments