[英]orderby () containing numbers and letters
I want to order an array containing numbers and letters in an ascending order the values are stored as a string in a DB. 我想按升序对包含数字和字母的数组进行排序,这些值作为字符串存储在数据库中。
This is the list I have 这是我的清单
4B
1A
1
1B
2
4C
4
and want them to order like this where numbers are ascending followed by letters alphabetically. 并希望他们在数字升序后跟字母的顺序排序。
1
1A
1B
2
4
4B
4C
So far I tried 到目前为止,我尝试了
allScenes.OrderBy(x => Convert.ToInt32(x.SceneNumber)).ToList()
and 和
allScenes.OrderBy(x => Convert.int.parse(x.SceneNumber)).ToList()
but both don't work because of the letters after the number. 但由于数字后面的字母,两者都不起作用。 Any idea how I can make this work?
知道如何使这项工作有效吗?
Given your example data where the first number is always a single digit: 给定您的示例数据,其中第一个数字始终是一个数字:
allScenes.OrderBy(x => x.SceneNumber).ToList()
If you can possibly have multi-digit numbers, please provide them and where you want them in the sort order. 如果您可能拥有多位数的数字,请按排序顺序提供它们以及您希望在何处显示它们。
This is one way to sort multiple digit numbers: 这是对多个数字进行排序的一种方法:
var allScenes = new[]{
new {SceneNumber="4B"},
new {SceneNumber="1A"},
new {SceneNumber="1"},
new {SceneNumber="1B"},
new {SceneNumber="2"},
new {SceneNumber="14"},
new {SceneNumber="4C"},
new {SceneNumber="14A"},
new {SceneNumber="200"},
new {SceneNumber="200A"},
new {SceneNumber="200B"}
};
var nums="0123456789".ToCharArray();
var result=allScenes
.OrderBy(x=>x.SceneNumber.LastIndexOfAny(nums))
.ThenBy(x=>x.SceneNumber);
Results: 结果:
1
1A
1B
2
4B
4C
14
14A
200
200A
200B
The database may not be able to convert the LastIndexOfAny function to something SQL-like, so you may need to do an .ToList() before the .OrderBy(): 数据库可能无法将LastIndexOfAny函数转换为类似SQL的内容,因此您可能需要在.OrderBy()之前执行.ToList():
var nums="0123456789".ToCharArray();
var result=allScenes
.ToList()
.OrderBy(x=>x.SceneNumber.LastIndexOfAny(nums))
.ThenBy(x=>x.SceneNumber);
Very simple 很简单
string[] allScenes = {"4B","1A","1","1B","2","4C"};
var result = allScenes.OrderBy(x => x.First()).ThenBy(x => x.Last());
As values are stored as string
into the database you just have to write OrderBy(e=> e)
. 当值以
string
形式存储到数据库中时,您只需要编写OrderBy(e=> e)
。
The code below proves this works: 下面的代码证明了这项工作:
string[] items = {"4B", "1A", "1", "1B", "2", "4C", "4"};
items.OrderBy(e=> e)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.