问题描述
我正在尝试对实际上是一个数字字符串的值进行排序。当我尝试使用LINQ对值进行排序时,我无法获得正确的排序数据。
Say.if我按升序对值进行排序{
Hi,
I am trying to sort the values which is actually a seminumeric string.When i try to sort the values using LINQ i cant able to get the proper sorted data.
Say.if i am sorting the value in ascending order{
"121212-1","121212-7","121212-6","121212-16",121212-4",
"121212-15",
"121212-14"
}
查询.OrderBy(list => list)
我得到正确的输出.KIndly帮我分类数字。
我已经尝试过这里提供的解决方案
[] br />
但它没有帮助我...
问候,
Hsakarp。
}
with the query .OrderBy(list => list)
I am getting the proper output.KIndly help me to sort the seminumeric number.
I ahve tried the solution provided here
[^]
but it didnot helped me...
Regards,
Hsakarp.
推荐答案
1
10
11
12
...
19
2
20
...
你需要做的就是将它们转换为数字。也许,最好的方法是使用一个类,但是快速而肮脏的方法是这样做:
What you need to do is convert them to numbers are sort those. Probably, the best way is to use a class, but a quick and dirty method would be to do this:
List<string> list = new List<string>(){ "121212-1","121212-7","121212-6","121212-16","121212-4","121212-15","121212-14"};
list = list.OrderBy(x => int.Parse(x.Split('-')[0])).ThenBy(x => int.Parse(x.Split('-')[1])).ToList();
foreach (string s in list)
{
Console.WriteLine(s);
}
但是你需要确保每个字符串都是正确的格式,否则你将得到空引用或解析错误!
But you would need to be sure that every string was in the right format first or you will get null reference or parse errors!
IList<string> list = new List<string>
{
"121212-1",
"121212-7",
"121212-6",
"121212-16",
"121212-4",
"121212-15",
"121213-14",
"121212-14"
};
Console.WriteLine("unsorted");
foreach(string s in list) Console.WriteLine(s);
/**
Output:
121212-1
121212-7
121212-6
121212-16
121212-4
121212-15
121213-14
121212-14
**/
IList<string> sortedList = list
.Select(s => s.Split(new[]{"-"}, StringSplitOptions.RemoveEmptyEntries))
.OrderBy(a => Int32.Parse(a[0]))
.ThenBy(a => Int32.Parse(a[1]))
.Select(a => String.Join("-", a))
.ToList();
Console.WriteLine("sorted");
foreach(string s in sortedList) Console.WriteLine(s);
/**
Ouput:
121212-1
121212-4
121212-6
121212-7
121212-14
121212-15
121212-16
121213-14
**/
这篇关于对数字字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!