1

I have Dictionary<string, int>. I want to get my int value by string key, but ignore string case.

I just figured out, that I can use Dictionary<TKey,TValue> constructor with IComparer parameter and Dictionary will use it to compare keys.

But do I have to write IComparer<string> implementation myself?

Kamil
  • 13,363
  • 24
  • 88
  • 183
  • You mean StringComparison.OrdinalIgnoreCase ? "There is also a static String.Compare(String, String, StringComparison) method that performs a case-insensitive ordinal comparison if you specify a value of StringComparison.OrdinalIgnoreCase for the StringComparison argument." – Severin Pappadeux Nov 03 '20 at 02:28
  • How are you using the dictionary and the comparer? Do you have some code you can show us? – Super Jade Nov 03 '20 at 21:06

1 Answers1

3

Yes, the StringComparer class provides a bunch of convenient StringComparer instances (which implement IComparer<string>) that does case-insensitive comparison:

  • 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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313