'Sorting out a list alphabetically then ascending

Imagine I have a list with the following values:

{"abc","04","bca","10","cba","11","01"}

if I use normal c# OrderBy() on the list it will result in this:

{"01","04","10","11","abc","bca","cba"}

but what I intend is a bit the opposite:

{"abc","bca","cba","01","04","10","11"}

How can I achieve this?



Solution 1:[1]

What about below solution,

var input = new List<string>(){"abc","04","bca","10","cba","11","01"};
var result = input.OrderBy(x => x.All(Char.IsDigit));

//You can further sort it, using `ThenBy()`
var result = input.OrderBy(x => x.All(Char.IsDigit)).ThenBy(x => x);

Try Online


Explaination:

  • x.All(Char.IsDigit) returns true if the all characters are digits. Otherwise it return false.

  • As we are writing it as a predicate, OrderBy() will sort the list based on the result of .All().

  • All false values will come first(In our case, non numeric strings) and all numeric strings will sort at the end

Solution 2:[2]

You could split the list by Regex into two lists, alphabet and numerical, then sort and then join them again.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 b166er