如何使用c#window应用程序按升序对字母数字进行排序 [英] How to sort alphanumeric in ascending order using c# window application
问题描述
我必须在文本框中显示Po-1,Po-2,Po-3 ......,Po-10,Po-11。
我在sql查询中尝试了它的工作,但是在c#窗口应用程序表单中它没有用。
如何纠正这个问题。
我尝试了什么:
我在sql查询中尝试过
通过CAST选择来自Goods_Inward顺序的ORDNo(LEFT(ORDNo,CHARINDEX(' - ',ORDNo)-1)AS VARCHAR)它的工作原理和输出为Po-1,Po-2 ...,Po-10 ,Po-11。
我在表格中使用过同样的查询,但它来自Po-1,Po-10,Po-11,Po-2,
Po- 3,....
即使在SQL中它也不能用于字符串:字符串总是逐字符比较,整个比较基于第一个区别。所以数字作为字符串的排序顺序总是看起来很奇怪
1
10
11
12
...
19
2
20
21
...为了获得正确的排序顺序,您需要将数字部分转换为数字,并对其进行排序。
假设您有一个List< string>然后它也不错:
myList = myList.OrderBy(s = > s.Substring( 0 ,s.IndexOf( - )))。ThenBy(s = > int .Parse(s.Substring(s.IndexOf) ( - )+ 1 ) ))ToList();
I have to show Po-1,Po-2,Po-3......,Po-10,Po-11 in textbox.
I have tried in sql query its works but in c# window application form it didn't work.
how to rectify this problem.
What I have tried:
I have tried in sql query as
select ORDNo from Goods_Inward order by CAST(LEFT(ORDNo,CHARINDEX('-',ORDNo)-1) AS VARCHAR)its works and i got the output as Po-1,Po-2...,Po-10,Po-11.
this same query i have used in Forms but it comes Po-1,Po-10,Po-11,Po-2,
Po-3,....
Even in SQL it won't work with strings: strings always compare character by character, and the whole comparison is based on the first difference. So the sort order for numbers as strings is always "odd looking"
1 10 11 12 ... 19 2 20 21 ...In order to get a "proper" sort order, you need to convert the numeric part to a number, and sort on that.
Assuming you have a List<string> then it's not too bad:
myList = myList.OrderBy(s => s.Substring(0, s.IndexOf("-"))).ThenBy(s => int.Parse(s.Substring(s.IndexOf("-") + 1))).ToList();
这篇关于如何使用c#window应用程序按升序对字母数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!