user2206329
user2206329

Reputation: 2842

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?

Upvotes: 16

Views: 40859

Answers (2)

Farhad Jabiyev
Farhad Jabiyev

Reputation: 26665

  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);
    

Upvotes: 30

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

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.

Upvotes: 6

Related Questions