本文介绍了LINQ-to-SQL 中不区分大小写的字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到使用 ToUpper 和 ToLower 来执行不区分大小写的字符串比较是不明智的,但我认为在 LINQ-to-SQL 方面别无选择.String.Compare 的 ignoreCase 和 CompareOptions 参数被 LINQ-to-SQL 忽略(如果您使用区分大小写的数据库,即使您要求不区分大小写的比较,也会得到区分大小写的比较).ToLower 或 ToUpper 是这里的最佳选择吗?这个比那个好吗?我以为我在某处读到 ToUpper 更好,但我不知道这是否适用于这里.(我做了很多代码审查,每个人都在使用 ToLower.)

I've read that it's unwise to use ToUpper and ToLower to perform case-insensitive string comparisons, but I see no alternative when it comes to LINQ-to-SQL. The ignoreCase and CompareOptions arguments of String.Compare are ignored by LINQ-to-SQL (if you're using a case-sensitive database, you get a case-sensitive comparison even if you ask for a case-insensitive comparison). Is ToLower or ToUpper the best option here? Is one better than the other? I thought I read somewhere that ToUpper was better, but I don't know if that applies here. (I'm doing a lot of code reviews and everyone is using ToLower.)

Dim s = From row In context.Table Where String.Compare(row.Name, "test", StringComparison.InvariantCultureIgnoreCase) = 0

这转化为一个 SQL 查询,它只是将 row.Name 与test"进行比较,并且不会在区分大小写的数据库上返回Test"和TEST".

This translates to an SQL query that simply compares row.Name with "test" and will not return "Test" and "TEST" on a case-sensitive database.

推荐答案

正如您所说,ToUpper 和 ToLower 之间存在一些重要差异,当您尝试进行不区分大小写的相等性检查时,只有一个是可靠准确的.

As you say, there are some important differences between ToUpper and ToLower, and only one is dependably accurate when you're trying to do case insensitive equality checks.

理想情况下,进行不区分大小写的相等性检查的最佳方法应该是:

Ideally, the best way to do a case-insensitive equality check would be:

String.Equals(row.Name, "test", StringComparison.OrdinalIgnoreCase)

注意,但是在这种情况下这不起作用!因此,我们坚持使用 ToUpperToLower.

NOTE, HOWEVER that this does not work in this case! Therefore we are stuck with ToUpper or ToLower.

注意 OrdinalIgnoreCase 以使其安全.但您使用的大小写(不)敏感检查的确切类型取决于您的目的.但通常在排序时使用 Equals 进行相等性检查和 Compare,然后为工作选择正确的 StringComparison.

Note the OrdinalIgnoreCase to make it security-safe. But exactly the type of case (in)sensitive check you use depends on what your purposes is. But in general use Equals for equality checks and Compare when you're sorting, and then pick the right StringComparison for the job.

Michael Kaplan(公认的文化和性格处理方面的权威)在 ToUpper 与 ToLower 上发表了相关帖子:

Michael Kaplan (a recognized authority on culture and character handling such as this) has relevant posts on ToUpper vs. ToLower:

他说String.ToUpper – 使用 ToUpper 而不是 ToLower,并指定 InvariantCulture 以获取操作系统大小写规则"

He says "String.ToUpper – Use ToUpper rather than ToLower, and specify InvariantCulture in order to pick up OS casing rules"

这篇关于LINQ-to-SQL 中不区分大小写的字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 13:32