Caselessly comparing strings in C#

前端 未结 6 1196
别那么骄傲
别那么骄傲 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

    The main thing you should be concerned about isn't performance, it's correctness, and from that aspect the method you probably want to be using for a case insensitive comparison is either:

    string.Compare(a, b, StringComparison.OrdinalIgnoreCase) == 0;
    

    or

    a.Equals(b, StringComparison.OrdinalIgnoreCase)
    

    (The first one is useful if you know the strings may be null; the latter is simpler to write if you already know that at least one string is non-null. I've never tested the performance but assume it will be similar.)

    Ordinal or OrdinalIgnoreCase are a safe bet unless you know you want to use another comparison method; to get the information needed to make the decision read this article on MSDN.

提交回复
热议问题