LINQ和CASE灵敏度 [英] LINQ and CASE Sensitivity
问题描述
我有这个LINQ查询:
I have this LINQ Query:
TempRecordList = new ArrayList(TempRecordList.Cast<string>().OrderBy(s => s.Substring(9, 30)).ToArray());
它工作得很好,并且以一种准确的方式执行排序,但是与我想要的有点不同.在查询结果中,我看到这样的内容:
It works great and performs sorting in a way that's accurate but a little different from what I want. Among the the result of the query I see something like this:
彼得·布特(Palm-Bouter),彼得
肖恩·帕尔默·约翰逊
Palm-Bouter, Peter
Palmer-Johnson, Sean
我真正需要的是对名称进行如下排序:
Whereas what I really need is to have names sorted like this:
肖恩·帕默·约翰逊
彼得·布伯特(Peter Palm-Bouter)
Palmer-Johnson, Sean
Palm-Bouter, Peter
基本上,我希望将'-'字符视为比该字符低的字符,以便稍后在升序搜索中显示包含该字符的名称.
Basically I want the '-' character to be treated as being lower than the character so that names that contain it show up later in an ascending search.
这是另一个例子.我得到:
Here is another example. I get:
雷金纳德·迪亚斯,
DiBlackley,安东
Dias, Reginald
DiBlackley, Anton
代替:
安东DiBlackley
雷迪纳尔·迪亚斯(迪亚斯)
DiBlackley, Anton
Dias, Reginald
如您所见,再次,由于大写字母'B'的处理方式,顺序被切换.
As you can see, again, the order is switched due to how the uppercase letter 'B' is treated.
所以我的问题是,我需要在LINQ查询中进行哪些更改以使其按我指定的顺序返回结果.任何反馈都将不胜感激.
So my question is, what do I need to change in my LINQ query to make it return results in the order I specified. Any feedback would be greatly appreaciated.
顺便说一句,我尝试使用 s.Substring(9,30).ToLower(),但这无济于事.
By the way, I tried using s.Substring(9, 30).ToLower() but that didn't help.
谢谢!
推荐答案
要自定义排序顺序,您将需要创建一个实现IComparer<string>
接口的比较器类. OrderBy()
方法将比较器作为第二个参数.
To customize the sorting order you will need to create a comparer class that implements IComparer<string>
interface. The OrderBy()
method takes comparer as second parameter.
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;
}
}
这至少适用于以下测试用例:
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"
这篇关于LINQ和CASE灵敏度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!