Determining Whether a String Is Contained Within a String Array (Case Insensitive)

Published 09 March 10 02:14 PM | Scott Mitchell

About once every couple of months I need to write a bit of code that does one thing if a particular string is found within an array of strings and something else if it is not ignoring differences in case. For whatever reason, I never seem to remember the code snippet to accomplish this, so after spending 10 minutes of research today I thought I'd write it down here in an effort to help commit it to memory or, at the very least, serve as a quick place to find the answer when the need arises again.

So without further adieu, here it is:

Visual Basic Version:

If stringArrayName.Contains("valueToLookFor", StringComparer.OrdinalIgnoreCase) Then
    ...
Else
    ...
End If

C# Version:

if (stringArrayName.Contains("valueToLookFor", StringComparer.OrdinalIgnoreCase))
    ...
else
    ...

Without the StringComparer.OrdinalIgnoreCase the search will be case-sensitive. For more information on comparing strings, see: New Recommendations for Using Strings in Microsoft .NET 2.0.

Happy Programming!

Filed under:

Comments

No Comments

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.