我使用CaseInsensitiveComparer.DefaultInvariant时发现一些非常奇怪的排序行为。以破折号“ - ”开头的单词最终被排序,好像没有破折号一样,而不是按照其他标点符号一样排在字母前面。
所以,给定 { "hello", ".net", "-less"},结果为{".net", "hello", "-less" },而不是预期的{"-less", ".net", "hello"}。
换言之,作为一个测试案例:
[TestMethod]
public void TestMethod1()
{
var rg = new String[] {
"x", "z", "y", "-less", ".net", "- more", "a", "b"
};
Array.Sort(rg, CaseInsensitiveComparer.DefaultInvariant);
Assert.AreEqual(
"- more,-less,.net,a,b,x,y,z",
String.Join(",", rg)
);
}
...这种情况下会出现失败:
Assert.AreEqual failed.
Expected:<- more,-less,.net,a,b,x,y,z>.
Actual: <- more,.net,a,b,-less,x,y,z>.
有什么想法是怎么回事吗?
编辑:
看起来,默认情况下,.NET在对字符串进行排序时会进行一些花哨的操作,导致前导连字符被排序到奇怪的位置,使得co-op和coop一起排序。因此,如果您希望您的前导连字符单词以其他标点符号的方式出现在开头,则必须告诉它不要这样做:
Array.Sort(rg, (a, b) => String.CompareOrdinal(a, b));