Case sensitive LINQ

How to make the LINQ register case-sensitive and NOT case-sensitive, depending on the situation?

I am using SQL Server 2008 and Entity Framework 4.0.

I modified COLLATION to make SQL Server case sensitive. so for such scenarios:

 query = query.Where(x => x.Username == username);

It works great. However, I need to be able to pull data from db ignoring the case when searching by topic (or name or the like) as follows:

query = query.Where(x => (x.Name.Contains(Name)));

which does not work when the record is "TestString" and I am looking for "test" or "test" or the like. How can I make it so that when it finds text or part of a line in text? thank

+5
source share
4 answers

LINQ does not have a notion of case sensitivity; it only cares about logical evaluation. Therefore, if you want to ignore the case, you should do something like:

query = query.Where(x => (x.Name.ToLower().Contains(Name.ToLower())));

Most likely, you need to pass CultureInfoto ToLower () (or use it ToLowerInvariant()), and you may need to cache the result Name.ToLower()in order not to perform this operation potentially a large number of times, but this should help you get started.

+11
source
query = query.Where(x => string.Equals(x.Name, Name, StringComparison.CurrentCultureIgnoreCase));
+5
source

Queryable.Contains IEqualityComparer<T>, . . msdn. , - , .

+1

:

String.Equals()

, , : -)

Ah ... and if you need to convert to the same case to make comparisons, ToUpper is better than ToLower. Do not ask me why. But you can read here: String Comparison in LINQ-to-SQL

0
source

All Articles