简体   繁体   English

按字母顺序排列列表然后升序

[英]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:如果我在列表中使用正常的 c# OrderBy() 它将导致:

{"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?我怎样才能做到这一点?

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.如果所有字符都是数字,则x.All(Char.IsDigit)返回true Otherwise it return false .否则返回false

  • As we are writing it as a predicate, OrderBy() will sort the list based on the result of .All() .由于我们将其写为谓词, OrderBy()将根据.All()的结果对列表进行排序。

  • All false values will come first(In our case, non numeric strings) and all numeric strings will sort at the end所有false值都将排在第一位(在我们的例子中,非数字字符串),所有数字字符串将排在最后

You could split the list by Regex into two lists, alphabet and numerical, then sort and then join them again.您可以通过 Regex 将列表拆分为两个列表,字母和数字,然后排序,然后再次加入它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM