Case insensitive string compare in LINQ

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

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.


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)

Note the Ordinal IgnoreCase 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 (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
  • He says "String.ToUpper – Use ToUpper rather than ToLower, and specify InvariantCulture in order to pick up OS casing rules "


    I used System.Data.Linq.SqlClient.SqlMethods.Like(row.Name, "test") in my query.

    This performs a case-insensitive comparison.


    我试着用Lambda表达式,它工作。

    List<MyList>.Any (x => (String.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) && (x.Type == qbType) );

    链接地址: http://www.djcxy.com/p/13076.html

    上一篇: 不区分大小写的JavaScript字符串比较

    下一篇: 在LINQ中不区分大小写的字符串比较