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?
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With