.NET での文字列比較推奨事項

.NET での文字列比較ですが、忘れやすいのでメモしておきます。

  • DO: Use StringComparison.Ordinal or OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  • DO: Use StringComparison.Ordinal and OrdinalIgnoreCase comparisons for increased speed.
  • DO: Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.
  • DO: Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when the comparison is linguistically irrelevant (symbolic, for example).
  • DO: Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.
  • DON'T: Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.
  • DON'T: Use StringComparison.InvariantCulture-based string operations in most cases; one of the few exceptions would be persisting linguistically meaningful but culturally-agnostic data.

上記もまとまっていますが、より簡単にまとめます。

日本語や英語など言語 (カルチャ) を考慮しない場合、 String.Compare() に StringComparison.Ordinal か StringComparison.OrdinalIgnoreCase を渡すと、文字列の比較を高速に行うことができます。 String.CompareOrdinal() を使用しても OK です。