Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Sorting alphabetical order a - z and then to aa, ab - zz

Tags:

c#

linq

I am looking for a solution in LINQ but anything helps (C#).

I tried using Sort() but its not working for example i have a sample list that contains

{"a", "b", "f", "aa", "z", "ac", "ba"}

the response I get is:

a, aa, ac, b, ba,  f, z 

and what I want is:

a, b, f, z, aa, ac, ba. 

any idea on a good unit test for this method? just to text that it is getting sorted that way.

like image 845
LuDevGon Avatar asked Jan 03 '20 21:01

LuDevGon


2 Answers

This should do it.

var data = new List<string>() { "a", "b", "f", "aa", "z", "ac", "ba" };
var sorted = data.OrderBy(x => x.Length).ThenBy(x => x);

Result:

a, b, f, z, aa, ac, ba

like image 172
Sach Avatar answered Sep 23 '22 18:09

Sach


If you are looking to actually order an existing list, you likely want to use the OrderBy() series of methods (e.g. OrderBy(), OrderByDescending(), ThenBy(), ThenByDescending()):

var orderedList = yourList.OrderBy(x => x.Length)
                          .ThenBy(x => x);

Example

You can find a working, interactive example here which would output as follows:

a,b,f,z,aa,ac,ba

like image 37
Rion Williams Avatar answered Sep 20 '22 18:09

Rion Williams