Cameron Castillo Cameron Castillo - 2 months ago 7
C# Question

Check for substring existance in an array c#

I believe there should be a duplicate question, but I just can't find it, so apologies if it is a duplicate.

I've got an array of items, and I would like to test the existence of another string. Now to test that I know I can use:

if (stringArray.Any(myItem.Contains))


But that does not seem to work with substrings. Is there a way to test for substrings without the use of a for-loop?

string[] stringArray = {"string1Item", "string2Item", "string3Item" };
//Test if "1" appears in array
if (stringArray.Any("1".Contains)) //returns false

Answer

You can do:

if (stringArray.Any(s => s.Contains("1")))

You were testing for the reverse, namely if the string "1" contains any of the strings in the array, which is obviously false.