gpt4 book ai didi

c# - 使用 StringComparison.Ordinal 对 String 进行排序的最简单方法

转载 作者:行者123 更新时间:2023-11-30 13:30:44 26 4
gpt4 key购买 nike

我发现了一个由 String.CompareTo 导致的错误(在我的代码中)和二进制搜索,因为我的自定义 IComparer(用于包装类型)使用 String.Compare(x, y, StringComparison.Ordinal)

这是因为 items.OrderBy(i => i.Name)(其中 Name 是字符串类型)用于构建要搜索的数组使用字符串对象本身作为 IComparable - 等等有不同的规则:

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] 根据序数比较 - 因为不是,所以二分搜索失败。

现在,随着“上下文”的出现,

使用与 String.Compare(.., StringComparison.Ordinal) 相同的字符串属性对对象进行排序的最简单方法(例如,无需为字符串实现自定义 IComparer)是什么?


编辑:我 [刚刚意识到我] 可以而且可能应该只使用 OrderBy(x => x, theSameComparer) - 但假设这是不可能的,OrderBy 如何与结果一样吗?

最佳答案

有一个适用于 StringComparison.Ordinal 的预构建 StringComparer - 那是 StringComparer.Ordinal :

items.OrderBy(i => i.Name, StringComparer.Ordinal)

关于c# - 使用 StringComparison.Ordinal 对 String 进行排序的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28638714/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com