我需要将一些字符串比较从vb转换为C#。 VB代码使用>和

[TestMethod]
public void TestMethod2()
{
    string originalCulture = CultureInfo.CurrentCulture.Name; // en-GB

    var a = "d".CompareTo("t");  // returns -1
    var b = "T".CompareTo("t");  // returns 1

    Assert.IsTrue(a < 0, "Case 1");
    Assert.IsTrue(b <= 0, "Case 2");
}

有人可以解释为什么b返回1。我目前的理解是,如果区分大小写,则“T”应按排序顺序(即-1)位于“t”之前。如果不区分大小写,则将相同,即0

(FYI .Net Framework 4.5.2)

很多thx

最佳答案

小写字母先于大写字母。
对于en-GB和InvariantCulture都是如此。

如果您想要类似ASCII的行为,则应指定其他的CompareOptions.Ordinal参数

请参阅以下内容:

  • Difference between InvariantCulture and Ordinal string comparison
  • C# sorting strings small and capital letters

  • repl.it上的示例代码:
    using System;
    using System.Globalization;
    using System.Collections.Generic;
    
    class MainClass
    {
        public static void Main(string[] args)
        {
    
            //All the following case sensitive comparisons puts d before D
            Console.WriteLine("D".CompareTo("d"));
            Console.WriteLine(String.Compare("D", "d", false));
            Console.WriteLine(String.Compare("D", "d", false, CultureInfo.InvariantCulture));
    
            //All the following case sensitive comparisons puts capital D before small letter d
            Console.WriteLine(String.Compare("D", "d", CultureInfo.InvariantCulture, CompareOptions.Ordinal));
    
            //The following is case insensitive
            Console.WriteLine(String.Compare("D", "d", true));
    
            //The default string ordering in my case is d before D
            var list = new List<string>(new[] { "D", "d" });
            list.Sort();
            foreach (var s in list)
            {
                Console.WriteLine(s);
            }
        }
    }
    
    //Results on repl.it
    //Mono C# compiler version 4.0.4.0
    //
    //1
    //1
    //1
    //-32
    //0
    //d
    //D
    

    祝你好运

    艾尔

    10-05 22:22