13

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

Idrees Khan
  • 7,702
  • 18
  • 63
  • 111

2 Answers2

18

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;
}
Alex Kovanev
  • 1,858
  • 1
  • 16
  • 29
  • 10
    This won't work if working directly on EF objects. Can't translate `IndexOf()` – Rufix Sep 25 '13 at 13:01
  • 15
    Doesn't Work with Entity Framework 5. LINQ to Entities does not recognize the method 'Int32 IndexOf(System.String, System.StringComparison)' method, and this method cannot be translated into a store expression – Jatin Nov 24 '13 at 12:51
7

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..

Matt Roberts
  • 26,371
  • 31
  • 103
  • 180