Bor*_*ens 15 c# sorting formatting tostring
我有一个字符串列表,可以包含一个字母或一个int的字符串表示(最多2位数).它们需要按字母顺序排序,或者(当它实际上是一个int时)对它所代表的数值进行排序.
例:
IList<string> input = new List<string>()
{"a", 1.ToString(), 2.ToString(), "b", 10.ToString()};
input.OrderBy(s=>s)
// 1
// 10
// 2
// a
// b
Run Code Online (Sandbox Code Playgroud)
我想要的是
// 1
// 2
// 10
// a
// b
Run Code Online (Sandbox Code Playgroud)
我有一些想法涉及通过尝试解析它来格式化它,然后如果它是一个成功的tryparse用我自己的自定义stringformatter格式化它使它有前面的零.我希望能有更简单,更高效的东西.
编辑
我最终制作了一个IComparer,我将其转储到我的Utils库中供以后使用.
当我在它的时候,我也在混合物中投掷了双打.
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);
}
Run Code Online (Sandbox Code Playgroud)
LBu*_*kin 21
我想到了两种方式,不确定哪种方式更具性能.实现自定义IComparer:
class MyComparer : IComparer<string>
{
public int Compare(string x, string y)
{
int xVal, yVal;
var xIsVal = int.TryParse( x, out xVal );
var yIsVal = int.TryParse( y, out yVal );
if (xIsVal && yIsVal) // both are numbers...
return xVal.CompareTo(yVal);
if (!xIsVal && !yIsVal) // both are strings...
return x.CompareTo(y);
if (xIsVal) // x is a number, sort first
return -1;
return 1; // x is a string, sort last
}
}
var input = new[] {"a", "1", "10", "b", "2", "c"};
var e = input.OrderBy( s => s, new MyComparer() );
Run Code Online (Sandbox Code Playgroud)
或者,将序列拆分为数字和非数字,然后对每个子组进行排序,最后加入排序结果; 就像是:
var input = new[] {"a", "1", "10", "b", "2", "c"};
var result = input.Where( s => s.All( x => char.IsDigit( x ) ) )
.OrderBy( r => { int z; int.TryParse( r, out z ); return z; } )
.Union( input.Where( m => m.Any( x => !char.IsDigit( x ) ) )
.OrderBy( q => q ) );
Run Code Online (Sandbox Code Playgroud)