Why does “-less” sort after “hello” instead of before it?

后端 未结 4 1269
心在旅途
心在旅途 2021-01-05 17:19

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 w

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 17:22

    To sort the strings in the way you need, you have to create a comparer class that compares strings using the Compareinfo class. This class allow you to specify various methods of comparison, the one that best matches yor needs is OrdinalIgnoreCase.

    From MSDN:

    Ignored Search Values

    Comparison operations, such as those performed by the IndexOf or LastIndexOf methods, can yield unexpected results if the value to search for is ignored. The search value is ignored if it is an empty string (""), a character or string consisting of characters having code points that are not considered in the operation because of comparison options, or a value with code points that have no linguistic significance. If the search value for the IndexOf method is an empty string, for example, the return value is zero.

    Note
    When possible, the application should use string comparison methods that accept a CompareOptions value to specify the kind of comparison expected. As a general rule, user-facing comparisons are best served by the use of linguistic options (using the current culture), while security comparisons should specify Ordinal or OrdinalIgnoreCase.specify Ordinal or OrdinalIgnoreCase.

    I have modified your test case, and this one execute correctly:

    public class MyComparer:Comparer
    {
        private readonly CompareInfo compareInfo;
    
        public MyComparer()
        {
            compareInfo = CompareInfo.GetCompareInfo(CultureInfo.InvariantCulture.Name);
        }
    
        public override int Compare(string x, string y)
        {
            return compareInfo.Compare(x, y, CompareOptions.OrdinalIgnoreCase);
        }
    }
    
    public class Class1
    {
        [Test]
        public void TestMethod1()
        {
            var rg = new String[] { 
        "x", "z", "y", "-less", ".net", "- more", "a", "b"
    };
    
            Array.Sort(rg, new MyComparer());
    
            Assert.AreEqual(
                "- more,-less,.net,a,b,x,y,z",
                String.Join(",", rg)
            );
    
    
        }
    }
    

提交回复
热议问题