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?
CodePudding user response:
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 even sort it, strings and numbers using `ThenBy()`
var result = input.OrderBy(x => x.All(Char.IsDigit)).ThenBy(x => x);
Explaination:
x.All(Char.IsDigit)
returnstrue
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 stirngs) and all numeric strings will sort at the end
CodePudding user response:
You could split the list by Regex into two lists, alphabet and numerical, then sort and then join them again.