gpt4 book ai didi

c# - 当字符串为数字时,如何在计算值的同时按字母顺序对字符串进行排序?

转载 作者:IT王子 更新时间:2023-10-29 03:37:36 24 4
gpt4 key购买 nike

我正在尝试对字符串数字数组进行排序,我希望它们按数字排序。

问题是我无法将数字转换为 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”。该数组可以是这样的:

string[] things= new string[] { "paul", "bob", "lauren", "007", "90" };

这意味着它需要按字母顺序和数字排序:

007, 90, bob, lauren, paul

最佳答案

将自定义比较器传递给 OrderBy。 Enumerable.OrderBy会让你指定任何你喜欢的比较器。

这是一种方法:

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);
}
}

关于c# - 当字符串为数字时,如何在计算值的同时按字母顺序对字符串进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6396378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com