Caselessly comparing strings in C#

前端 未结 6 1197
别那么骄傲
别那么骄傲 2020-12-17 16:21

Let\'s say I have two strings: a and b. To compare whether a and be have the same values when case is ignored, I\'ve always used:

// (Assume a and b have bee         


        
6条回答
  •  囚心锁ツ
    2020-12-17 17:04

    When comparing strings you should always use an explicit StringComparison member. The String functions are somewhat inconsistent in how they choose to compare strings. The only way to guarantee the comparision used is to a) memorize all of them (this includes both you and everyone on your team) or b) use an explicit comparison for every function.

    It's much better to be explicit and not rely on group knowledge being perfect. Your teammates will thank you for this.

    Example:

    if ( StringComparison.OrdinalIgnoreCase.Equals(a,b) )
    

    Using ToLower for comparison has 2 problems I can think of off the top of my head

    1. It allocates memory. Comparison functions should not allocate memory unless they absolutely have to.
    2. Strings can be lowered in several ways. Most notable Ordinal or Culture Sensitive lower. Which way does .ToLower() work? Personally, I don't know. It's much better to pass an explicit culture than rely on the default.

提交回复
热议问题