acr*_*ige 4 .net c# sorting string
我想对字符串区分大小写:如果一个以大写"C"开头,那么它应该比以"c"开头但比小于以"d"开头的那个"更大"(例如). .
例如,排序列表:"a","A","chi","Che","Chr"
编写的字符串比较方法默认区分大小写.但看起来我对"区分大小写"的理解与默认情况不同.
我尝试过的默认方法(String.CompareTo
,String.Compare
(使用不同的StringComparison
值))都没有给出我想要的结果.
这是我用于测试的代码:
using System;
using System.Collections.Generic;
public class Test
{
public static void Main()
{
var list = new List<String> { "Che", "Chr", "chi", "a", "A" };
// Any other way to sort goes here
list.Sort((s1, s2) => s1.CompareTo(s2));
for (var i = 0; i < list.Count; i++)
{
Console.WriteLine(list[i]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个代码恰好给出了结果:"a""A""Che""chi""Chr".这么小的"c"站在"C"之间.
所以,问题是:有没有办法用任何默认方法实现我想要的排序顺序(看起来非常明显),而无需编写我自己的比较器?我错过了什么吗?
我没有看到除编写自己的比较器之外的其他方式,因为在字符串方面的非海峡逻辑:a < A < c < C
= 97 < 65 < 99 < 67
.
sealed class CustomComparer : Comparer<string>
{
public override int Compare(string x, string y)
{
for (int i = 0; i < Math.Min(x.Length, y.Length); i++)
{
char xc = x[i];
char yc = y[i];
if (xc == yc)
continue;
char xcLow = char.ToLowerInvariant(xc);
char ycLow = char.ToLowerInvariant(yc);
if (xcLow == ycLow)
return xc < yc ? 1 : -1;
else
return xcLow < ycLow ? -1 : 1;
}
return x.Length.CompareTo(y.Length);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
var list = new List<String> { "Che", "Chr", "chi", "a", "A" };
list.Sort(new CustomComparer()); // a, A, chi, Che, Chr
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
726 次 |
最近记录: |