LINQ and CASE Sensitivity

后端 未结 4 971
花落未央
花落未央 2021-01-22 16:57

I have this LINQ Query:

TempRecordList = new ArrayList(TempRecordList.Cast().OrderBy(s => s.Substring(9, 30)).ToArray());

It w

4条回答
  •  时光取名叫无心
    2021-01-22 17:58

    To customize the sorting order you will need to create a comparer class that implements IComparer interface. The OrderBy() method takes comparer as second parameter.

    internal sealed class NameComparer : IComparer {
        private static readonly NameComparer DefaultInstance = new NameComparer();
    
        static NameComparer() { }
        private NameComparer() { }
    
        public static NameComparer Default {
            get { return DefaultInstance; }
        }
    
        public int Compare(string x, string y) {
            int length = Math.Min(x.Length, y.Length);
            for (int i = 0; i < length; ++i) {
                if (x[i] == y[i]) continue;
                if (x[i] == '-') return 1;
                if (y[i] == '-') return -1;
                return x[i].CompareTo(y[i]);
            }
    
            return x.Length - y.Length;
        }
    }
    

    This works at least with the following test cases:

    var names = new[] {
        "Palmer-Johnson, Sean",
        "Palm-Bouter, Peter",
        "Dias, Reginald",
        "DiBlackley, Anton",
    };
    
    var sorted = names.OrderBy(name => name, NameComparer.Default).ToList();
    
    // sorted:
    // [0]: "DiBlackley, Anton"
    // [1]: "Dias, Reginald"
    // [2]: "Palmer-Johnson, Sean"
    // [3]: "Palm-Bouter, Peter"
    

提交回复
热议问题