Reputation: 2842
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
Reputation: 26665
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));
You could also use IndexOf
overload 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
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