C#LINQ的OrderBy数字是字符串(你不能将它们转换为int) [英] c# linq orderby numbers that are string (and you cannot convert them to int)
问题描述
我想排序是串数字数组,我想他们数值排序。
I'm trying to sort an array of numbers that are strings and I'd like them to sort numerically.
美中不足的是,我无法将数字转换成INT
下面是code:
string[] things= new string[] { "105", "101", "102", "103", "90" };
foreach (var thing in things.OrderBy(x => x))
{
Console.WriteLine(thing);
}
输出:101,102,103,105,90
output: 101, 102, 103, 105, 90
我想:90,101,102,103,105
I'd like: 90, 101, 102, 103, 105
编辑:
输出不能是090,101,102 ...
The output can't be 090, 101, 102...
更新了code样品说事而非尺寸。该阵列可以是这样的:
Updated the code sample to say "things" instead of "sizes". The array can be something like this:
string[] things= new string[] { "paul", "bob", "lauren", "007", "90" };
这意味着它需要按字母顺序排序,并以数字:
That means it needs to be sorted alphabetically and by number:
007,90,鲍勃,劳伦,保罗
007, 90, bob, lauren, paul
推荐答案
传递一个自定义比较成排序依据。 Enumerable.OrderBy 会让你指定任何你喜欢的比较器。
Pass a custom comparer into OrderBy. Enumerable.OrderBy will let you specify any comparer you like.
这是做到这一点的一种方法:
This is one way to do that:
void Main()
{
string[] things= new string[] { "paul", "bob", "lauren", "007", "90", "101"};
foreach (var thing in things.OrderBy(x => x, new SemiNumericComparer()))
{
Console.WriteLine(thing);
}
}
public class SemiNumericComparer: IComparer<string>
{
public int Compare(string s1, string s2)
{
if (IsNumeric(s1) && IsNumeric(s2))
{
if (Convert.ToInt32(s1) > Convert.ToInt32(s2)) return 1;
if (Convert.ToInt32(s1) < Convert.ToInt32(s2)) return -1;
if (Convert.ToInt32(s1) == Convert.ToInt32(s2)) return 0;
}
if (IsNumeric(s1) && !IsNumeric(s2))
return -1;
if (!IsNumeric(s1) && IsNumeric(s2))
return 1;
return string.Compare(s1, s2, true);
}
public static bool IsNumeric(object value)
{
try {
int i = Convert.ToInt32(value.ToString());
return true;
}
catch (FormatException) {
return false;
}
}
}
这篇关于C#LINQ的OrderBy数字是字符串(你不能将它们转换为int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!