2

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.

dns_nx
  • 3,651
  • 4
  • 37
  • 66

2 Answers2

5

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);
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

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)))
Community
  • 1
  • 1
user1666620
  • 4,800
  • 18
  • 27