问题描述
我正在尝试对一组数字进行排序,这些数字是字符串,并且希望对它们进行数字排序.
I'm trying to sort an array of numbers that are strings and I'd like them to sort numerically.
要注意的是,我无法将数字转换为int .
这是代码:
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...
将代码示例更新为说东西"而不是大小".数组可以是这样的:
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
推荐答案
将自定义比较器传递到OrderBy. Enumerable.OrderBy 将允许您指定所需的任何比较器.
Pass a custom comparer into OrderBy. Enumerable.OrderBy will let you specify any comparer you like.
这是一种实现方法:
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>
{
/// <summary>
/// Method to determine if a string is a number
/// </summary>
/// <param name="value">String to test</param>
/// <returns>True if numeric</returns>
public static bool IsNumeric(string value)
{
return int.TryParse(value, out _);
}
/// <inheritdoc />
public int Compare(string s1, string s2)
{
const int S1GreaterThanS2 = 1;
const int S2GreaterThanS1 = -1;
var IsNumeric1 = IsNumeric(s1);
var IsNumeric2 = IsNumeric(s2);
if (IsNumeric1 && IsNumeric2)
{
var i1 = Convert.ToInt32(s1);
var i2 = Convert.ToInt32(s2);
if (i1 > i2)
{
return S1GreaterThanS2;
}
if (i1 < i2)
{
return S2GreaterThanS1;
}
return 0;
}
if (IsNumeric1)
{
return S2GreaterThanS1;
}
if (IsNumeric2)
{
return S1GreaterThanS2;
}
return string.Compare(s1, s2, true, CultureInfo.InvariantCulture);
}
}
这篇关于当字符串为数字时,如何在按值排序时按字母顺序对字符串进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!