C# Comparing strings with different case [duplicate]
I'm reading a username and then checking to see if exists in another database table, the problem is whilst the username is the same the case maybe different and is preventing it from finding a match example jsmith and JSmith or JSMITH.
How can I fix this? Should I lower the case when writing to the first database or can I alter my code below when I'm comparing the two?
drUser["Enrolled"] =
(enrolledUsers.FindIndex(x => x.Username == (string)drUser["Username"]) != -1);
UPDATE:
Still struggling with this, the code below compiles b开发者_如何学Cut doesn't give the correct result, when viewing enrolled users I see those that aren't enrolled, when viewing those that are not enrolled I see 1 that is enrolled but their username case is the same in each datababse. Have I formatted the code below correctly?
drUser["Enrolled"] = (enrolledUsers.FindIndex(x => x.Username.Equals((string)drUser["Username"], StringComparison.OrdinalIgnoreCase)));
Thanks Jamie
You need to cal the Equals
method, which takes a StringComparison
parameter.
For example:
x.Username.Equals((string)drUser["Username"], StringComparison.OrdinalIgnoreCase)
If x.Username
can be null
, you should call the static Equals
method:
String.Equals(x.Username, (string)drUser["Username"], StringComparison.OrdinalIgnoreCase)
Otherwise, x.Username.Equals
can throw a NullReferenceException
.
The preferred way to do this, is to specify the string comparison by using something like
string.Equals(x.Username, (string)drUser["Username"], StringComparison.OrdinalIgnoreCase
to do the equality check, instead of "=="
Have you tried this?
string userName = (string)drUser["Username"];
bool enrolled = enrolledUsers.Exists(x =>
string.Equals(x.Name, userName, StringComparison.CurrentCultureIgnoreCase));
Is there a reason you are using FindIndex instead?
try the string.compare method. all overloads
Or a more specific one
If nothing else, I hope it educates.
How about using ToUpper().
if(!(dr["Enrolled"] == null || dr["Username"] == null))
{
if(dr["Enrolled"].ToString().ToUpperInvariant()== dr["Username"].ToString().ToUpperInvariant())
{
//Do Something
}
}
精彩评论