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
Patricia ArquetteOriginal
2025-01-19 12:46:09150browse

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>

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>

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>

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!

Statement:
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