Vinod
Vinod

Reputation: 4882

Linq Contains doesn't work on List

Items
Code
A
B
C

from x in Items where(x.Code.Contains("a")) select x  //This Linq returns A


from x in Items.ToList() where(x.Code.Contains("a")) select x //This Linq returns nothing

In the second Linq it has become Case Sensitive may i know why and how to overcome this.

Upvotes: 1

Views: 1868

Answers (3)

Martin Costello
Martin Costello

Reputation: 10862

SQL server is case-insensitive using the default collation, so either case will work when the SQL query is executed against the database. When you call ToList(), all the items are fetched from the database and put in a case sensitive List<T>, then the items are filtered. As the List<T> is case-sensitive, it will return false for lowercase values.

You should be using the first code you have, as otherwise in the case of a large table you will have performance issues as you will basically be doing a SELECT * FROM with the second code.

Upvotes: 2

Jonathan Hiben
Jonathan Hiben

Reputation: 553

It's probably because your first query is Linq-To-SQL, so case insensitive, while your second query is Linq-To-Objects, so pure objects with all that comes with it. Then simply do the following:

from x in Items.ToList() where(x.Code.ToLower().Contains("a")) select x

It should do the work.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460158

I assume that this is LINQ-To-SQL or some other LINQ provider that translates it to SQL. The database is case insentitive by default but C# is not. When you call ToList you create an in-memory list. Since x.Code seems to be a String you are using String.Contains which looks for sub-strings case-sensitive.

You can use String.IndexOf with StringComparison.OrdinalIgnoreCase if you want:

from x in Items.ToList() 
where(x.Code.IndexOf("a", StringComparison.OrdinalIgnoreCase) >= 0) 
select x 

Upvotes: 1

Related Questions