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

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

Linda Hamilton
Release: 2025-01-19 13:01:09
Original
512 people have browsed it

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

Case-insensitive string comparison in C#

String comparison in C# is case-sensitive by default. This means that when comparing two strings, any difference in case will cause the strings to be considered unequal. However, there are situations where case-insensitive comparisons are required, such as matching user input or identifying unique values ​​in a database.

Consider the following code:

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

This code checks whether the current user is registered by comparing the registered user's "Username" attribute with the current user's "Username" attribute. However, if the usernames have different case, the comparison will fail.

To make this comparison case-insensitive, you can use the String.Equals method and the StringComparison.OrdinalIgnoreCase parameter:

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

However, the above code does not produce the expected results. This is because of the equality operator (==) used in FindIndex lambda expressions, which always performs case-sensitive comparisons.

To resolve this issue, follow MSDN's advice and use the String.Equals method as the only comparison operator:

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

This code checks whether the current user is registered in a case-insensitive manner, allowing usernames to have different case.

The above is the detailed content of How to Perform Case-Insensitive String Comparisons 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