Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Check if string contains any matches in a string array

What would be the fastest way to check if a string contains any matches in a string array in C#? I can do it using a loop, but I think that would be too slow.

like image 820
rayanisran Avatar asked Nov 16 '10 04:11

rayanisran


2 Answers

Using LINQ:

 return array.Any(s => s.Equals(myString))

Granted, you might want to take culture and case into account, but that's the general idea. Also, if equality is not what you meant by "matches", you can always you the function you need to use for "match".

like image 87
Esteban Araya Avatar answered Oct 07 '22 20:10

Esteban Araya


I really couldn't tell you if this is absolutely the fastest way, but one of the ways I have commonly done this is:

This will check if the string contains any of the strings from the array:

string[] myStrings = { "a", "b", "c" };
string checkThis = "abc";

if (myStrings.Any(checkThis.Contains))
{
    MessageBox.Show("checkThis contains a string from string array myStrings.");
}

To check if the string contains all the strings (elements) of the array, simply change myStrings.Any in the if statement to myStrings.All.

I don't know what kind of application this is, but I often need to use:

if (myStrings.Any(checkThis.ToLowerInvariant().Contains))

So if you are checking to see user input, it won't matter, whether the user enters the string in CAPITAL letters, this could easily be reversed using ToLowerInvariant().

Hope this helped!

like image 28
SomeRandomProgrammer Avatar answered Oct 07 '22 21:10

SomeRandomProgrammer