Home > Backend Development > C++ > How to Perform Case-Insensitive String Comparisons Correctly in C#?

How to Perform Case-Insensitive String Comparisons Correctly in C#?

Patricia Arquette
Release: 2025-01-19 12:46:09
Original
149 people have browsed it

How to Perform Case-Insensitive String Comparisons Correctly in C#?

Case-insensitive string comparison in C#

When doing string comparisons in C#, you usually need to ignore case. While you might initially consider using the StringComparison.OrdinalIgnoreCase method with Equals, this may lead to unexpected results.

In the following code example:

<code class="language-csharp">drUser["Enrolled"] = 
      (enrolledUsers.FindIndex(x => x.Username.Equals((string)drUser["Username"], 
                                 StringComparison.OrdinalIgnoreCase)));</code>
Copy after login

The problem is using the Equals method with an expression lambda. The expression lambda expects a boolean expression, but the Equals method returns void.

In .NET Framework 4 and above, it is recommended to use the String.Compare method combined with StringComparison.OrdinalIgnoreCase for case-insensitive string comparison, as shown below:

<code class="language-csharp">String.Compare(x.Username, (string)drUser["Username"], 
                  StringComparison.OrdinalIgnoreCase) == 0</code>
Copy after login

Alternatively, to make the code more readable and less error-prone, you can use the String.Equals method, like this:

<code class="language-csharp">String.Equals(x.Username, (string)drUser["Username"], 
                   StringComparison.OrdinalIgnoreCase) </code>
Copy after login

These methods ensure that string comparisons are performed in a case-insensitive manner, providing accurate results.

The above is the detailed content of How to Perform Case-Insensitive String Comparisons Correctly in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template