简体   繁体   English

如何测试字符串是否包含列表中的项目?

[英]How to test if a string contains an item within a list?

Say I have a string: 说我有一个字符串:

var s = "z_cams_c_ecmf_20160704120000_prod_fc_ml_012_go3.nc";

and say I have a list of strings: 并说我有一个字符串列表:

var items = new List<string>(){"fc", "an"};

How can I test if s contains either fc or an ? 如何测试s包含fcan

I don't want to loop over items and test each case because I am looking for multiple conditions. 我不想遍历items并测试每个案例,因为我正在寻找多个条件。 For example, I will also want to test if s contains "prod" or "rean" or "test". 例如,我还将要测试s包含“ prod”或“ rean”或“ test”。

I suppose I could throw all my conditions ( fc , an , prod , rean , test , etc...) into single list and iterate over each of them, but it doesn't feel right, given the user must supply JSON which is deseralized into an object with various lists for condition matching. 我想我可以将所有条件( fcanprodreantest等)放入单个列表并遍历每个条件,但是由于用户必须提供JSON,因此感觉不对。反序列化为具有各种条件匹配列表的对象。

I suppose I am looking for something like the answer seen here , but I do not know what Mdd LH is... 我想我正在寻找类似此处所示答案的内容,但是我不知道Mdd LH是什么...

LINQ also uses loops, but you don't see them ;-) LINQ也使用循环,但是您看不到它们;-)

bool contains = items.Any(s.Contains);

If you want to ignore the case(so upper or lowercase letters): 如果要忽略大小写(大写或小写字母):

contains = items.Any(i => s.IndexOf(i, StringComparison.InvariantCultureIgnoreCase) >= 0); 

暂无
暂无

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

相关问题 如何删除包含特定字符串的列表中的项目 - How to remove an item in a list that contains specific string 如何测试列表是否包含字符串的一部分 - How to test if a list contains part of a string 检查字符串列表是否包含项目 - Check if a string list contains an item 如何在词典中查找键 <int,List<Tuple<string,string> &gt;&gt;,以使列表包含具有给定Item1和Items的元素 - How to find keys in a Dict<int,List<Tuple<string,string>>> such that the list contains elements with given Item1 and Items 如何将“int”数据类型项转换为“字符串”并使用 LINQ 中的“包含”在字符串列表中搜索? - How to convert an 'int' data type item to 'string' and search in a string list using 'Contains' in LINQ? 获取列表中包含其他列表中每个字符串的每个项目 - Get every item in a list that contains every string in an other list 如何读取Type IDictionary的数据<string,entitytype>包含值的集合...如何在 List 集合中读取此项目</string,entitytype> - How read the data of Type IDictionary<string,EntityType> contains collection of values... how to read this item in List collection 如何检查字典是否包含列表中的项目 - How to check if a dictionary contains an item in a list 检查列表中的字符串是否包含Linq的特定字符串 - Check if a string within a list contains a specific string with Linq 使用 C# Linq 测试字符串是否包含字符串列表的一部分 - Using C# Linq to test if string contains parts of a list of string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM