user2206329 user2206329 - 10 days ago 4x
C# Question

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?

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