How can I do a case insensitive string comparison?

How can I make the line below case insensitive?

drUser["Enrolled"] = 
      (enrolledUsers.FindIndex(x => x.Username == (string)drUser["Username"]) != -1);

I was given some advice earlier today that suggested I use:

x.Username.Equals((string)drUser["Username"], StringComparison.OrdinalIgnoreCase)));

the trouble is I can't get this to work, I've tried the line below, this compiles but returns the wrong results, it returns enrolled users as unenrolled and unenrolled users as enrolled.

drUser["Enrolled"] = 
      (enrolledUsers.FindIndex(x => x.Username.Equals((string)drUser["Username"], 
                                 StringComparison.OrdinalIgnoreCase)));

Can anyone point out the problem?


This is not the best practice in .NET framework (4 & +) to check equality

String.Compare(x.Username, (string)drUser["Username"], 
                  StringComparison.OrdinalIgnoreCase) == 0

Use the following instead

String.Equals(x.Username, (string)drUser["Username"], 
                   StringComparison.OrdinalIgnoreCase) 

MSDN recommends:

  • Use an overload of the String.Equals method to test whether two strings are equal.
  • Use the String.Compare and String.CompareTo methods to sort strings, not to check for equality .

  • 你应该使用如下的静态String.Compare函数

    x => String.Compare (x.Username, (string)drUser["Username"],
                         StringComparison.OrdinalIgnoreCase) == 0
    

    请使用这个比较:

    string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
    
    链接地址: http://www.djcxy.com/p/75228.html

    上一篇: linq不区分大小写(没有toUpper或toLower)

    下一篇: 我如何做一个不区分大小写的字符串比较?