简体   繁体   中英

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 ?

I don't want to loop over items and test each case because I am looking for multiple conditions. For example, I will also want to test if s contains "prod" or "rean" or "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.

I suppose I am looking for something like the answer seen here , but I do not know what Mdd LH is...

LINQ also uses loops, but you don't see them ;-)

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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