Nick Kahn
Nick Kahn

Reputation: 20078

How to make Case-In-Sensitive with Linq

EDIT:

Also like to know: what if; if i have a data that is not upper case? or have mixed of upper or lower case? how you will handle this?

i am trying to query my resultset

IQueryable<CategoryObject>  filteredCategories = _catRepo.GetAllEmployees();


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

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

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

OR

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

OR

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

The result should be the same

Upvotes: 2

Views: 130

Answers (3)

pil0t
pil0t

Reputation: 2185

First way, as said before - use ToUpper():

var filterString = "bLoCkS"
filteredCategories = categoriesList.Where(c=> c.CategoryName.ToUpper().Contains(filterString.ToUpper()));

Another way - use Case Insensetive collation (Changing SQL Server collation to case insensitive from case sensitive?) in your database (table, field).

Upvotes: 1

dkackman
dkackman

Reputation: 15559

You can also try:

filteredCategories = categoriesList.Where(c=> c.CategoryName.IndexOf("blocks", StringComparison.OrdinalIgnoreCase) != -1);

Upvotes: 2

Andrew
Andrew

Reputation: 2335

Try

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

That'll remove any case issues.

Upvotes: 4

Related Questions