dns_nx
dns_nx

Reputation: 3953

C# - using string contains with string array

I have a question regarding C#, strings and arrays. I've searched for similar questions at stack overflow, but could not find any answers.

My problem:

I have a string array, which contains words / wordparts to check file names. If all of these strings in the array matches, the word is "good".

String[] StringArray = new String[] { "wordpart1", "wordpart2", ".txt" };

Now I want to check if all these strings are a part of a filename. If this checkresult is true, I want to do something with this file. How can I do that?

I already tried different approaches, but all doesn't work.

i.e.

e.Name.Contains(StringArray)

etc.

I want to avoid to use a loop (for, foreach) to check all wordparts. Is this possible? Thanks in advance for any help.

Upvotes: 2

Views: 944

Answers (2)

user1666620
user1666620

Reputation: 4808

Similar question: Using C# to check if string contains a string in string array

This uses LINQ:

if(stringArray.Any(stringToCheck.Contains))

This checks if stringToCheck contains any one of substrings from stringArray. If you want to ensure that it contains all the substrings, change Any to All:

if(stringArray.All(s => stringToCheck.Contains(s)))

Upvotes: 3

Selman Genç
Selman Genç

Reputation: 101721

Now I want to check if all these strings are a part of a filename. If this checkresult is true, I want to do something with this file. How can I do that?

Thanks to LINQ and method groups conversions, it can be easily done like this:

bool check = StringArray.All(yourFileName.Contains);

Upvotes: 5

Related Questions