简体   繁体   中英

Check if any of the items in a list satisfy a condition

I have a list of 11 items as follows

List<string> telcos = new List<string> { "024", "054", "055", "027", "057", "020", "050", "026", "056", "023", "028" };

Now I am trying to compare from the list items to see if at least one of the items is equal to the strings I am comparing with. If any one of the items is equal to my string comparison, the loop should stop but I am getting a repeated loop which is giving me an error.

foreach (string fonItem in telcos)
{
   if (frm["txtPhoneNumberField"].Substring(0, 3) != fonItem)
   {
       for (int i = 0; i < loopFoneCount; i++)
       {
           listOfPhonesEdit.Add(frm["PhoneNumberTextBox" + i]);
           ViewBag.ListOfPhonesEdit = listOfPhonesEdit;
       }

      this.redisplay();
      return View(customerModel);
   }

}

I need you help.

Your question is unclear, but, if your objective is to add a series of PhoneNumberTextBox if the prefix present in frm["txtPhoneNumberField"] matches one of the prefixes listed in your telcos list, then you could write:

// Extract the prefix once and for all.....
string prefix = frm["txtPhoneNumberField"].Substring(0, 3) 

// Is the prefix listed in telcos?
if(telcos.Any(x => x==prefix)
{
     for (int i = 0; i < loopFoneCount; i++)
        listOfPhonesEdit.Add(frm["PhoneNumberTextBox" + i]);

     // This should be outside the for loop otherwise you get only the 
     // last number in frm....
     ViewBag.ListOfPhonesEdit = listOfPhonesEdit;

     // I am uncertain if these two lines should be inside the if or not.
     this.redisplay();
     return View(customerModel);
}
....

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