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.
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
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);
You can find a working, interactive example here which would output as follows:
a,b,f,z,aa,ac,ba
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With