当字符串是数字时,如何在考虑值的同时按字母顺序对字符串进行排序? [英] How do I sort strings alphabetically while accounting for value when a string is numeric?
本文介绍了当字符串是数字时,如何在考虑值的同时按字母顺序对字符串进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试对作为字符串的数字数组进行排序,并且我希望它们按数字进行排序.
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
我愿意:
90, 101, 102, 103, 105
输出不能是 090, 101, 102...
将代码示例更新为things
";而不是sizes
".数组可以是这样的:
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, 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);
}
}
这篇关于当字符串是数字时,如何在考虑值的同时按字母顺序对字符串进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文