gpt4 book ai didi

.net - 当 “sides” 都是数字时,如何将字母数字值排序为数字?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:13 25 4
gpt4 key购买 nike

我们在网格中有一些包含数字、字符串或以数字开头的字符串的列,用户希望它们以合理的方式排序。 (格式取决于客户,因此我们不知道字符串的格式)

是否有 IComparable 的预制“实现可以执行类似的操作?

最佳答案

这里是一个快速的字母数字排序(也可以用于其他带有数字的排序)。

C# 字母数字排序 http://www.dotnetperls.com/alphanumeric-sorting

var unordered = new[] { "100F", "50F", "SR100", "SR9" };
var ordered = unordered.OrderBy(s => s, new AlphanumComparatorFast());

这是一篇关于这个问题的好文章:

人类排序:自然排序顺序 http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html

这是 AlphanumComparatorFast 类,以防上述链接停止工作页面末尾声明“它可以在任何程序中不受限制地使用”,代码开头的注释也表示它是免费使用的:

// NOTE: This code is free to use in any program.
// ... It was developed by Dot Net Perls.

public class AlphanumComparatorFast : IComparer
{
public int Compare(object x, object y)
{
string s1 = x as string;
if (s1 == null)
{
return 0;
}
string s2 = y as string;
if (s2 == null)
{
return 0;
}

int len1 = s1.Length;
int len2 = s2.Length;
int marker1 = 0;
int marker2 = 0;

// Walk through two the strings with two markers.
while (marker1 < len1 && marker2 < len2)
{
char ch1 = s1[marker1];
char ch2 = s2[marker2];

// Some buffers we can build up characters in for each chunk.
char[] space1 = new char[len1];
int loc1 = 0;
char[] space2 = new char[len2];
int loc2 = 0;

// Walk through all following characters that are digits or
// characters in BOTH strings starting at the appropriate marker.
// Collect char arrays.
do
{
space1[loc1++] = ch1;
marker1++;

if (marker1 < len1)
{
ch1 = s1[marker1];
}
else
{
break;
}
} while (char.IsDigit(ch1) == char.IsDigit(space1[0]));

do
{
space2[loc2++] = ch2;
marker2++;

if (marker2 < len2)
{
ch2 = s2[marker2];
}
else
{
break;
}
} while (char.IsDigit(ch2) == char.IsDigit(space2[0]));

// If we have collected numbers, compare them numerically.
// Otherwise, if we have strings, compare them alphabetically.
string str1 = new string(space1);
string str2 = new string(space2);

int result;

if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
{
int thisNumericChunk = int.Parse(str1);
int thatNumericChunk = int.Parse(str2);
result = thisNumericChunk.CompareTo(thatNumericChunk);
}
else
{
result = str1.CompareTo(str2);
}

if (result != 0)
{
return result;
}
}
return len1 - len2;
}
}

关于.net - 当 “sides” 都是数字时,如何将字母数字值排序为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8417176/

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