Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore case sensitivity in StartsWith for LINQ FindAll?

Tags:

I have the following code:

ContactList = ContactList.FindAll(p => p.DeptName.StartsWith(optAlpha.SelectedItem.Value)).ToList();

If DeptName="test" and optAlpha.SelectedItem.Value="T", it doesn't work.

I tried with the following code, still doesn't work.

ContactList = ContactList.FindAll(p => p.DeptName.ToLower().StartsWith(optAlpha.SelectedItem.Value.ToLower())).ToList();
like image 843
WinFXGuy Avatar asked May 22 '14 18:05

WinFXGuy


People also ask

Is StartsWith in C# case sensitive?

The String. startsWith method is case sensitive.

Are LINQ queries case sensitive?

LINQ has no concept of case sensitivity, it only cares about boolean evaluation. So if you want to ignore case, you should do something like: query = query.

How do you check if a string starts with a character in C#?

In C#, StartsWith() is a string method. This method is used to check whether the beginning of the current string instance matches with a specified string or not. If it matches then it returns the string otherwise false.


2 Answers

Just use

StartsWith(optAlpha.SelectedItem.Value, StringComparison.InvariantCultureIgnoreCase);

and it will ignore the case during the default comparison.

like image 103
Mike Perrenoud Avatar answered Sep 18 '22 14:09

Mike Perrenoud


No need to use ToLower you can just call an overload of starts with and pass it StringComparison.InvariantCultureIgnoreCase as the second arg (first being the string to compare). Here's the docs on string comparison options; http://msdn.microsoft.com/en-us/library/system.stringcomparison(v=vs.110).aspx

like image 45
evanmcdonnal Avatar answered Sep 19 '22 14:09

evanmcdonnal