Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ case sensitive

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

like image 360
ShaneKm Avatar asked Feb 24 '11 12:02

ShaneKm


People also ask

Is EF core case sensitive?

For one thing, EF Core does know not which case-sensitive or case-insensitive collation should be used. More importantly, applying a collation would in most cases prevent index usage, significantly impacting performance for a very basic and commonly-used . NET construct.

What is collation case insensitive?

What is collation? Collation is a set of rules that tells a database engine how to compare and sort the CHAR and VARCHAR columns data in SQL. A case-insensitive collation ignores the differences between uppercase and lowercase letters for string comparison and sorting, whereas a case-sensitive collation does not.

Is SQL Server case insensitive?

SQL Server is, by default case insensitive; however, it is possible to create a case sensitive SQL Server database and even to make specific table columns case sensitive. The way to determine a database or database object is by checking its “COLLATION” property and look for “CI” or “CS” in the result.

How use contains in Linq?

The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.


2 Answers

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:

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

Chances are you will want to pass a CultureInfo to ToLower() (or use ToLowerInvariant()), and you might want to cache the result of Name.ToLower() so as to not have to perform that operation a potentially large number of times, but this should get you started.

like image 183
user Avatar answered Sep 20 '22 15:09

user


query = query.Where(x => string.Equals(x.Name, Name, StringComparison.CurrentCultureIgnoreCase));
like image 35
Ivan Farkas Avatar answered Sep 20 '22 15:09

Ivan Farkas