问题描述
我有一个字符串列表,其中可以包含一个字母或一个 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.
这篇关于对混合数字和字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)