LINQ Contains Case Insensitive
这段代码区分大小写,如何区分大小写?
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM.Where(fi => fi.DESCRIPTION.Contains(description));
}
fi => fi.DESCRIPTION.ToLower().Contains(description.ToLower())
If the LINQ query is executed in database context, a call to Contains()
is mapped to the LIKE
operator:
.Where(a => a.Field.Contains("hello"))
becomes Field LIKE '%hello%'
. The LIKE
operator is case insensitive by default, but that can be changed by changing the collation of the column.
If the LINQ query is executed in .NET context, you can use IndexOf(), but that method is not supported in LINQ to SQL.
LINQ to SQL does not support methods that take a CultureInfo as parameter, probably because it can not guarantee that the SQL server handles cultures the same as .NET. This is not completely true, because it does support StartsWith(string, StringComparison)
.
However, it does not seem to support a method which evaluates to LIKE
in LINQ to SQL, and to a case insensitive comparison in .NET, making it impossible to do case insensitive Contains() in a consistent way.
假设我们在这里使用字符串,下面是使用IndexOf()
的另一个“优雅”解决方案。
public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
return this.ObjectContext.FACILITY_ITEM
.Where(fi => fi.DESCRIPTION
.IndexOf(description, StringComparison.OrdinalIgnoreCase) != -1);
}
链接地址: http://www.djcxy.com/p/75198.html
上一篇: 为什么pyglet比pygame慢得多?
下一篇: LINQ包含大小写不敏感