使用StringComparison.Ordinal对字符串进行排序的最简单方法 [英] Easiest method to OrderBy a String using StringComparison.Ordinal
问题描述
我发现了一个错误(在我的代码中),该错误是由 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:
该比较使用当前区域性来获取特定于区域性的信息,例如大小写规则和各个字符的字母顺序.例如,一种文化可以指定将某些字符组合视为单个字符,或者以特定方式比较大写和小写字符,或者字符的排序顺序取决于其前后的字符./p>
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?
推荐答案
有一个适用于StringComparison.Ordinal
-这是
There is a pre-built StringComparer
that applies StringComparison.Ordinal
- that's StringComparer.Ordinal
:
items.OrderBy(i => i.Name, StringComparer.Ordinal)
这篇关于使用StringComparison.Ordinal对字符串进行排序的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!