C# 比较不同大小写的字符串
我正在读取用户名,然后检查是否存在于另一个数据库表中,问题是虽然用户名相同,但大小写可能不同,并且阻止它找到匹配示例 jsmith 和 JSmith 或 JSMITH。
我该如何解决这个问题?在写入第一个数据库时是否应该降低大小写,或者在比较两者时可以更改下面的代码吗?
drUser["Enrolled"] =
(enrolledUsers.FindIndex(x => x.Username == (string)drUser["Username"]) != -1);
更新:
仍在努力解决这个问题,下面的代码可以编译,但没有给出正确的结果,当查看已注册的用户时,我看到那些未注册的用户,当查看那些未注册的用户时,我看到 1 已注册,但他们的用户名大小写每个数据库中都是相同的。我是否正确格式化了下面的代码?
drUser["Enrolled"] = (enrolledUsers.FindIndex(x => x.Username.Equals((string)drUser["Username"], StringComparison.OrdinalIgnoreCase)));
谢谢 杰米
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 but 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您需要计算
Equals
方法,它采用StringComparison
参数。例如:
如果
x.Username
可以为null
,则应调用静态Equals
方法:否则,
x.Username.Equals
可能会抛出NullReferenceException
。You need to cal the
Equals
method, which takes aStringComparison
parameter.For example:
If
x.Username
can benull
, you should call the staticEquals
method:Otherwise,
x.Username.Equals
can throw aNullReferenceException
.执行此操作的首选方法是通过使用类似
进行相等性检查的方式来指定字符串比较,而不是“==”
The preferred way to do this, is to specify the string comparison by using something like
to do the equality check, instead of "=="
你试过这个吗?
您使用 FindIndex 来代替有什么原因吗?
Have you tried this?
Is there a reason you are using FindIndex instead?
尝试 string.compare 方法。
所有重载
或更多 具体一个
如果没有别的,我希望它能有所启发。
try the string.compare method.
all overloads
Or a more specific one
If nothing else, I hope it educates.
使用 ToUpper() 怎么样。
How about using ToUpper().