How to make LINQ case sensitive and NOT case sensitive depending on the situation?
I'm using sql server 2008 and Entity Framework 4.0.
I changed the COLLATION to make SQL Server case sensitive. so that for scenarios like these:
query = query.Where(x => x.Username == username);
it works great.
However I need to be able to pull out data from db ignoring case when searching by subject (or name or similar) like so:
query = query.Where(x => (x.Name.Contains(Name)));
which doesn't work when record is "TestString" and i'm looking for "test" or "Test" or similar. How would i make it so that when it would find a text or part of a string in a text?
thanks
Best Answer
LINQ has no concept of case sensitivity, it only cares about boolean evaluation. So if you want to ignore case, you should do something like:
Chances are you will want to pass a
CultureInfo
to ToLower() (or useToLowerInvariant()
), and you might want to cache the result ofName.ToLower()
so as to not have to perform that operation a potentially large number of times, but this should get you started.