简体   繁体   English

C#-使用字符串包含与字符串数组

[英]C# - using string contains with string array

I have a question regarding C#, strings and arrays. 我对C#,字符串和数组有疑问。 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. 我有一个字符串数组,其中包含单词/ wordparts来检查文件名。 If all of these strings in the array matches, the word is "good". 如果数组中的所有这些字符串都匹配,则该单词为“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. 我已经尝试过不同的方法,但一切都行不通。

ie

e.Name.Contains(StringArray)

etc. 等等

I want to avoid to use a loop (for, foreach) to check all wordparts. 我想避免使用循环(for,foreach)来检查所有的字部分。 Is this possible? 这可能吗? Thanks in advance for any help. 在此先感谢您的帮助。

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: 感谢LINQ和方法组转换,它可以像这样轻松完成:

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

Similar question: Using C# to check if string contains a string in string array 类似的问题: 使用C#检查字符串是否包含字符串数组中的字符串

This uses LINQ: 这使用LINQ:

 if(stringArray.Any(stringToCheck.Contains)) 

This checks if stringToCheck contains any one of substrings from stringArray. 这将检查stringToCheck是否包含来自stringArray的子​​字符串中的任何一个。 If you want to ensure that it contains all the substrings, change Any to All: 如果要确保它包含所有子字符串,请将Any更改为All:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM