加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:45:33 所属栏目:百科 来源:网络整理
导读:我发现了一个由于 String.CompareTo和二进制搜索而导致的错误(在我的代码中),因为我的自定义IComparer(用于包装类型)使用String.Compare(x,y,StringComparison.Ordinal). 这是因为用于构建要搜索的Array的items.OrderBy(i = i.Name)(其中Name是string类型)使
我发现了一个由于 String.CompareTo和二进制搜索而导致的错误(在我的代码中),因为我的自定义IComparer(用于包装类型)使用String.Compare(x,y,StringComparison.Ordinal).

这是因为用于构建要搜索的Array的items.OrderBy(i => i.Name)(其中Name是string类型)使用字符串对象本身作为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,C],但按顺序比较应该是[b,A,C] – 因为它不是,二进制搜索失败.

现在,随着“背景”的出现,

什么是最简单的(例如,没有为字符串实现自定义IComparer)的方式来命令具有字符串属性的对象与String.Compare(..,StringComparison.Ordinal)相同?

编辑:我[刚刚意识到我]可以,也许应该只使用OrderBy(x => x,theSameComparer) – 但是假设这是不可能的,OrderBy如何使用相同的结果?

解决方法

有一个预先构建的StringComparer适用于 StringComparison.Ordinal – 即 StringComparer.Ordinal

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读