I'm seeing some very strange sorting behaviour using CaseInsensitiveComparer.DefaultInvariant. Words that start with a leading hyphen "-" end up sorted as if the hyphen wasn't there rather than being sorted in front of actual letters which is what happens with other punctuation.
So given { "hello", ".net", "-less"} I end up with {".net", "hello", "-less" } instead of the expected {"-less", ".net", "hello"}.
Or, phrased as a test case:
[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)
);
}
... which fails like this:
Assert.AreEqual failed.
Expected:<- more,-less,.net,a,b,x,y,z>.
Actual: <- more,.net,a,b,-less,x,y,z>.
Any ideas what's going on?
Edit:
Looks like, by default .NET does fancy things when sorting strings which causes leading hyphens to be sorted into strange places so that co-op and coop sort together. Thus, if you want your leading hyphen words to end up and the begining with the other punctutation you have to tell it not not to:
Array.Sort(rg, (a, b) => String.CompareOrdinal(a, b));