排序混合数字和字符串 [英] Sorting mixed numbers and strings

查看:129
本文介绍了排序混合数字和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以包含一个字母或一个int(最多2位)的字符串表示字符串列表。
他们需要按字母顺序排序或(当它实际上是一个int),它代表的数值



例如:

 的IList<串GT;输入=新列表与所述;串GT;()
{一,1.ToString(),2.ToString(),B,10.ToString()};

input.OrderBy(S = GT S)
// 1
// 10
// 2
//一个
// b

我想是

  // 1 
// 2
// 10
//一个
// b

我有一些想法涉及与试图解析它格式化,那么如果它是一个全成的TryParse将其与自己的自定义stringformatter格式化使其具有前述零。我希望更多的东西简单,高性能的。



修改

我最终作出的IComparer我甩在我的Utils库中供以后使用。

当我在这我扔在混合太双打。

 公共类MixedNumbersAndStringsComparer:的IComparer<串GT; {
公众诠释比较(字符串x,y字符串){
双XVAL,利用yval;

如果(double.TryParse(X,出XVAL)及和放大器; double.TryParse(Y,出利用yval))
返回xVal.CompareTo(利用yval);
,否则
返回的String.Compare(X,Y);
}
}

//测试在INT VS整型,双VS双,INT VS双,串VS整型,字符串VS域金字塔之戒,串VS字符串。
//不是要去把那些在这里
[TestMethod的]
公共无效RealWorldTest()
{
名单,LT;字符串>输入=新列表与所述;串GT;(){一,1,2,0,B,10};
名单,LT;字符串>预期=新列表与所述;串GT;(){1,2,0,10,一个,B};
input.Sort(新MixedNumbersAndStringsComparer());
CollectionAssert.AreEquivalent(预期,输入);
}


解决方案

也许你可以用一个去更通用的方法和使用自然排序算法如C#实现的here


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.

Example:

IList<string> input = new List<string>()
    {"a", 1.ToString(), 2.ToString(), "b", 10.ToString()};

input.OrderBy(s=>s)
  // 1
  // 10
  // 2
  // a
  // b

What I would want is

  // 1
  // 2
  // 10
  // a
  // b

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.

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

解决方案

Perhaps you could go with a more generic approach and use a natural sorting algorithm such as the C# implementation here.

这篇关于排序混合数字和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆