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

问题描述

我读过,这是不明智的使用ToUpper的和tolower执行不区分大小写字符串比较,但我看不出有什么替代方案,当涉及到LINQ到SQL。的String.Compare的IGNORECASE和CompareOptions参数通过LINQ到SQL忽略(如果您使用的是区分大小写的数据库,你会得到一个即使你问一个不区分大小写的比较区分大小写的比较)。是TOLOWER或ToUpper的这里最好的选择?是其中一个比另一个更好吗?我想我读的地方,ToUpper的是更好的,但我不知道这是否适用于这里。 (我做了很多code评论,每个人都使用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在区分大小写的数据库。

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 is:

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

请注意在 IGNORECASE,使其安全性安全。但是,情况完全(在)的类型使用敏感的检查取决于你的目的是什么。但在一般使用等于平等检查,当你排序比较,然后选择合适的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.

迈克尔·卡普兰(文化和字符处理像这样一个公认的权威)对ToUpper的与TOLOWER相关文章:

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

  • http://www.siao2.com/2007/10/01/5218976.aspx
  • http://www.siao2.com/2005/03/10/391564.aspx
  • http://www.siao2.com/2007/10/01/5218976.aspx
  • http://www.siao2.com/2005/03/10/391564.aspx

他说: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到SQL不区分大小写字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 07:51