Idrees Khan
Idrees Khan

Reputation: 7752

LINQ To Entities Contains Case In-Sensitive Searching

i am trying to query my resultset like this in linq to entities;

var categoriesList = _catRepo.GetAllCategories();


 filteredCategories = categoriesList.Where(c=> c.CategoryName.Contains("for"));

However, i don't get any result becuase the CategoryName is For(Upper Case) in the database. I have also checked the sql server collation and it is set to _CI_AS. I have no idea how to use contains to filter case insensitive string? I want basically if someone type like;

 filteredCategories = categoriesList.Where(c=> c.CategoryName.Contains("for"));

OR

filteredCategories = categoriesList.Where(c=> c.CategoryName.Contains("For"));

The result should be the same

Upvotes: 13

Views: 15080

Answers (2)

Alex Kovanev
Alex Kovanev

Reputation: 1888

Try this

filteredCategories = categoriesList.Where(c=>
 c.CategoryName.IndexOf("for", StringComparison.OrdinalIgnoreCase) >= 0)

Contains method works as shown below

public bool Contains(string value)
{
   return this.IndexOf(value, StringComparison.Ordinal) >= 0;
}

Upvotes: 18

Matt Roberts
Matt Roberts

Reputation: 26877

The previous IndexOf answer should work. Because you are loading all the entities from the database and then doing an in-memory (linq to objects) filter on it, you are not doing anything on the database at all.

This should also work (from the post I referenced)

filteredCategories = categoriesList.Where(c=> c.CategoryName.ToLower().Contains("for"));

Just an aside, if you have a lot of categories, then you might want to filter them on the database, rather than fetch all from the db and then filter them in memory..

Upvotes: 7

Related Questions