问题描述
我发现了一个由 String.CompareTo 和二进制搜索,因为我的自定义 IComparer(用于包装类型)使用 String.Compare(x, y, StringComparison.Ordinal)
.
I've found a bug (in my code) that results from String.CompareTo and binary search because my custom IComparer (for the wrapping type) uses String.Compare(x, y, StringComparison.Ordinal)
.
这是因为 items.OrderBy(i => i.Name)
(其中 Name 是字符串类型)用于构建要搜索的数组使用字符串对象本身作为 IComparable - 并且这样有不同的规则:
This is because items.OrderBy(i => i.Name)
(where Name is of type string) used to build the Array to search used the string object itself as the IComparable - and such has different rules:
比较使用当前文化来获取特定于文化的信息,例如大小写规则和单个字符的字母顺序.例如,文化可以指定某些字符组合被视为单个字符,或以特定方式比较大小写字符,或者字符的排序顺序取决于其前面或后面的字符.
The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.
例如,{A, b, C} 使用 OrderBy-using-Default-String-Compare 排序为 [A, b, C]
但应该是 [b,A, C]
根据序数比较 - 因为不是,所以二进制搜索失败.
For example, {A, b, C} is sorted as [A, b, C]
with the OrderBy-using-Default-String-Compare but should be [b, A, C]
per the Ordinal comparison - since it is not, the binary search is failing.
现在,把上下文"排除在外,
Now, with the "context" out of the way,
用与 String.Compare(.., StringComparison.Ordinal)
相同的字符串属性对对象进行排序的最简单方法是什么(例如,不为字符串实现自定义 IComparer)?
What is the easiest (eg. without implementing a custom IComparer for strings) way to order the objects with string properties the same as with String.Compare(.., StringComparison.Ordinal)
?
我 [刚刚意识到我] 可以而且可能应该只使用 OrderBy(x => x, theSameComparer)
- 但假设这是不可能的,如何使用 OrderBy结果一样吗?
I [just realized I] can, and probably should, just use OrderBy(x => x, theSameComparer)
- but supposing this wasn't possible, how can OrderBy be used with the same results?
推荐答案
有一个预建的 StringComparer
应用 StringComparison.Ordinal
- 那是 StringComparer.Ordinal
:
There is a pre-built StringComparer
that applies StringComparison.Ordinal
- that's StringComparer.Ordinal
:
items.OrderBy(i => i.Name, StringComparer.Ordinal)
这篇关于使用 StringComparison.Ordinal 对字符串进行排序的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!