简体   繁体   中英

how to know if a string contains any of the strings on a list?

I have this list:

List<string> lst01 = new List<string>();
lst01.Add("1");
lst01.Add("999");
lst01.Add("888");

List<string> lst02 = new List<string>();
lst02.Add("4");
lst02.Add("5");
lst02.Add("6");

string myString = "123";

I would like to know if myString contains any of the string of the list.

So the method would return true with the first list and false with the second.

Thanks so much.

 var result1 = lst01.Any(v=> myString.Contains(v));
 var result2 = lst02.Any(v=> myString.Contains(v));

You could try something like the below:

bool contains = lst01.Any(x=>x.myString.Contains(x))||list02.Any(x=>x.myString.Contains(x))

Or this one:

bool containedInFirstList =  lst01.Any(x=>x.myString.Contains(x));
bool containedInSecondList = lst02.Any(x=>x.myString.Contains(x));

The second apporach looks separately at the lists and in case of contained or not in the list you are looking for you will get either true or false .

The first approach does initially the same, however at the end get the logical OR of results you would get if you follow the second approach.

try below code here r1 returns true and r2 returns false :-

                List<string> lst01 = new List<string>();
                lst01.Add("1");
                lst01.Add("999");
                lst01.Add("888");

                List<string> lst02 = new List<string>();
                lst02.Add("4");
                lst02.Add("5");
                lst02.Add("6");

                string myString = "123";
                var r1 = lst01.Any(w => myString.Contains(w));
                var r2 = lst02.Any(w => myString.Contains(w));
string myString = "123";
for (int i=0, i<lst01.size , i++){
   if (myString.Contains(lst01[i]))
   {
       return true;

   }}
return false;

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