问题描述
我有一个字符串列表,其中可以包含一个字母或一个 int 的字符串表示形式(最多 2 位数字).它们需要按字母顺序或(当它实际上是一个 int 时)按它所代表的数值排序.
I have a list of strings that can contain a letter or a string representation of an int (max 2 digits). They need to be sorted either alphabetically or (when it is actually an int) on the numerical value it represents.
例子:
IList<string> input = new List<string>()
{"a", 1.ToString(), 2.ToString(), "b", 10.ToString()};
input.OrderBy(s=>s)
// 1
// 10
// 2
// a
// b
我想要的是
// 1
// 2
// 10
// a
// b
我有一些想法涉及格式化它并尝试解析它,然后如果它是一个成功的 tryparse 用我自己的自定义 stringformatter 格式化它以使其具有前面的零.我希望有更简单、更高效的东西.
I have some idea involving formatting it with trying to parse it, then if it is a successfull tryparse to format it with my own custom stringformatter to make it have preceding zeros. I'm hoping for something more simple and performant.
编辑
我最终制作了一个 IComparer,我将其转储到我的 Utils 库中以供以后使用.
当我这样做的时候,我也加入了双打.
Edit
I ended up making an IComparer I dumped in my Utils library for later use.
While I was at it I threw doubles in the mix too.
public class MixedNumbersAndStringsComparer : IComparer<string> {
public int Compare(string x, string y) {
double xVal, yVal;
if(double.TryParse(x, out xVal) && double.TryParse(y, out yVal))
return xVal.CompareTo(yVal);
else
return string.Compare(x, y);
}
}
//Tested on int vs int, double vs double, int vs double, string vs int, string vs doubl, string vs string.
//Not gonna put those here
[TestMethod]
public void RealWorldTest()
{
List<string> input = new List<string>() { "a", "1", "2,0", "b", "10" };
List<string> expected = new List<string>() { "1", "2,0", "10", "a", "b" };
input.Sort(new MixedNumbersAndStringsComparer());
CollectionAssert.AreEquivalent(expected, input);
}
推荐答案
也许您可以采用更通用的方法并使用 自然排序算法如C#实现这里.
Perhaps you could go with a more generic approach and use a natural sorting algorithm such as the C# implementation here.
这篇关于对混合数字和字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!