简体   繁体   English

.NET 是否有忽略大小写的 IComparer 实现<string> ?

[英]Does .NET have a case-ignoring implementation of IComparer<string>?

I have Dictionary<string, int> .我有Dictionary<string, int> I want to get my int value by string key, but ignore string case.我想通过字符串键获取我的 int 值,但忽略字符串大小写。

I just figured out, that I can use Dictionary<TKey,TValue> constructor with IComparer parameter and Dictionary will use it to compare keys.我刚刚发现,我可以使用带有IComparer参数的Dictionary<TKey,TValue>构造函数,并且Dictionary将使用它来比较键。

But do I have to write IComparer<string> implementation myself?但是我必须自己编写IComparer<string>实现吗?

Yes, the StringComparer class provides a bunch of convenient StringComparer instances (which implement IComparer<string> ) that does case-insensitive comparison:是的, StringComparer类提供了一堆方便的StringComparer实例(实现IComparer<string> )进行不区分大小写的比较:

  • CurrentCultureIgnoreCase
  • InvariantCultureIgnoreCase
  • OrdinalIgnoreCase

Without knowing any more of your use case, I can't tell you which comparer you want to use.在不了解您的用例的情况下,我无法告诉您要使用哪个比较器。 You need to think about which culture (or the invariant culture) you want the comparison to be in, or whether you want a simple ordinal comparison.您需要考虑您希望比较属于哪种文化(或不变文化),或者您是否希望进行简单的有序比较。


That said, Dictionary doesn't accept an IComparer , but an IEqualityComparer ... But you can still use StringComparer nonetheless, it also implements IEqualityComparer .也就是说, Dictionary不接受IComparer ,而是接受IEqualityComparer ......但是你仍然可以使用StringComparer ,它也实现了IEqualityComparer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM