Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# contains case insensitive search

I have the following code

var returnData = DemoData.Books.AsQueryable();

if (criteria.Author != string.Empty)
{
    returnData = returnData.Where(x => x.Author.Contains(criteria.Author));
}

How do I made the where clause case insensitive?

like image 960
user2206329 Avatar asked Apr 13 '14 07:04

user2206329


2 Answers

  1. You can use ToLower() function. ToLower changes strings to be all lowercase. It converts an entire string—without changing letters that are already lowercased or digits. It copies a string and returns a reference to the new string. So it is always better option to declare criteria.Author.ToLower() outside the query.

    string lowerAuthor = criteria.Author.ToLower();
    returnData = returnData.Where
            (x => x.Author.ToLower().Contains(lowerAuthor));
    
  2. You could also use IndexOfoverload with the StringComparison enum. It would give you better performance than ToLower(). The signature of this overload is:

    int string.IndexOf(string value, StringComparison comparisonType);
    

    returnData = returnData.Where
        (x => x.Author.IndexOf(criteria.Author, StringComparison.CurrentCultureIgnoreCase) != -1);
    
like image 114
Farhad Jabiyev Avatar answered Oct 23 '22 23:10

Farhad Jabiyev


returnData = returnData.Where
        (x => x.Author.IndexOf(criteria.Author, StringComparison.CurrentCultureIgnoreCase) != -1)

It will make no additional string allocation at all.

I assumed it's LINQ to Objects query.

like image 6
MarcinJuraszek Avatar answered Oct 24 '22 00:10

MarcinJuraszek