同时循环遍历两个列表并将每个项目传递给方法

时间:2016-03-31 06:27:17

标签: c# .net list c#-4.0 foreach

我有两个像这样的字符串列表

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

所以我在下面这样做

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

    }

这里我需要将每个项目的表单传递给方法 UpdateClpInternalLicense ,第二个列表( subscriptionList )有5项但我需要停止发送第5项那个方法..

我尝试了上面提到的方法,但问题是一旦内循环完成..它会再次循环,因为第一个列表中有4个项目..

我需要将每个列表中的一个项目传递给该方法,直到4次迭代,在第4次迭代之后,我需要从两个循环中出来..

请任何人提出任何想法,非常感激......

非常感谢...

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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

这会将其归结为您正在迭代的单个列表,然后break将起作用。