LINQ和CASE灵敏度

Gon*_*ght 2 linq sorting linq-to-objects case-sensitive

我有这个LINQ查询:

TempRecordList = new ArrayList(TempRecordList.Cast<string>().OrderBy(s => s.Substring(9, 30)).ToArray());
Run Code Online (Sandbox Code Playgroud)

它工作得很好,并以一种准确但与我想要的有点不同的方式进行排序.在查询的结果中,我看到这样的事情:

Palm-Bouter,Peter
Palmer-Johnson,Sean

而我真正需要的是将名称排序如下:

Palmer-Johnson,Sean
Palm-Bouter,Peter

基本上我希望' - '字符被视为低于字符,以便包含它的名称稍后在升序搜索中显示.

这是另一个例子.我明白了:

Dias,Reginald
DiBlackley,Anton

代替:

迪布拉克利,安东
迪亚斯,雷金纳德

正如您所看到的,由于大写字母"B"的处理方式,订单也会被切换.

所以我的问题是,我需要在LINQ查询中更改什么才能使其按照我指定的顺序返回结果.任何反馈都会得到极大的反响.

顺便说一句,我尝试使用s.Substring(9,30).ToLower(),但这没有帮助.

谢谢!

mgr*_*ber 6

要自定义排序顺序,您需要创建一个实现IComparer<string>接口的比较器类.该OrderBy()方法将比较器作为第二个参数.

internal sealed class NameComparer : IComparer<string> {
    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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这至少适用于以下测试用例:

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"
Run Code Online (Sandbox Code Playgroud)