Glory Raj
Glory Raj

Reputation: 17691

loop through two lists at the same time and passing each item to method

I have got two list of strings like this

list<string> OldlicenseList = new List<string>{"abcs", "rtets", "taya", "tctct"}; //sample data

list<string> subscriptionList = new List<string> {"udud", "ydyyd" , "tsts","tstst", "hghs"} //Sample data

so I am doing like this below

  foreach (var strOldLicense in OldlicenseList)
  {
         foreach (var subscriptionList in objSubscription.lstClsLicense)
         {
               newLicenseList.Add(subscriptionList.license_key);
               isInserted = _objcertificate.UpdateClpInternalLicense(subscriptionKey, _objUserInfo.GetUserAcctId(), strOldLicense, subscriptionList.license_key, expiryDT);

               if (!isInserted)
               {
                   new Log().logInfo(method, "Unable to update the Subscription key." + certID);
                   lblErrWithRenewSubKey.Text = "Application could not process your request. The error has been logged.";
                   lblErrWithRenewSubKey.Visible = true;
                   return;
               }
               insertCount++;

               if (insertCount >= 4)
               {
                        break;
               }
         }

    }

here i need pass each item form both the lists to the method UpdateClpInternalLicense and second list (subscriptionList ) is having 5 items but i need to stop sending 5 th item to that method..

I tried above mentioned way, but the problem is once inner loop is completed .. it will loop through again since there are 4 items in first list ..

I need to pass one item from each list to that method until 4 iterations, after 4th iteration i need to come out from both loops ..

Would any one please suggest any ideas, that would be very grateful ..

Many thanks in advance..

Upvotes: 0

Views: 435

Answers (1)

Enigmativity
Enigmativity

Reputation: 117029

You could do this:

var query =
    from strOldLicense in OldlicenseList
    from subscriptionList in objSubscription.lstClsLicense
    select new { strOldLicense, subscriptionList };

foreach (var x in query)
{
    newLicenseList.Add(x.subscriptionList.license_key);
    isInserted = _objcertificate.UpdateClpInternalLicense(subscriptionKey, _objUserInfo.GetUserAcctId(), x.strOldLicense, x.subscriptionList.license_key, expiryDT);

    if (!isInserted)
    {
        new Log().logInfo(method, "Unable to update the Subscription key." + certID);
        lblErrWithRenewSubKey.Text = "Application could not process your request. The error has been logged.";
        lblErrWithRenewSubKey.Visible = true;
        return;
    }
    insertCount++;

    if (insertCount >= 4)
    {
        break;
    }
}

This gets it down to a single list that you're iterating through so then the break will work.

Upvotes: 1

Related Questions