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!