如何迭代更改集合

Sea*_*her 1 .net c#

我有以下代码.

private void LoopThroughDependsIssues(JIRAOperations jiraOps, string jiraURL, string token, string username, string password, string projectKey, string exportTargetPath, string branch, SVNOperations svnOps, string svnExePath, string changesetDBFile, DependencyManager mgr)
        {
            var tempVar = mgr.Dependencies;
            foreach (var item in tempVar)
            {
                if (item.depends.Length > 0)
                {
                    var templist = item.depends;
                  var  listissues1 = templist.Split(',');
                     for (var i = 0; i < listissues1.Length-1; i++)
                     {
                         var newissue1 = new string[] { listissues1[i].ToString() };
                         newissue1.getChangeSet(jiraOps, jiraURL, token, username, password, projectKey, exportTargetPath, branch, svnOps, svnExePath, changesetDBFile, mgr);
                     }
                    //throw new Exception("Dependencies found");
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

在这里,我正在迭代mgr.Dependencis集合.此值正在改变.newissue1.getChangeSet(jiraOps, jiraURL, token, username, password, projectKey, exportTargetPath, branch, svnOps, svnExePath, changesetDBFile, mgr); 对于此方法的每次调用,我的集合值都在增加.但这是第一次它工作正常.但是,当第二次迭代时,它将异常作为

收集被修改; 枚举操作可能无法执行.

我认为这个例外即将发生变化.如何处理这种情况.

我的课程定义如下.

public class Dependency
     {
         public string issueID { get; set; }
         public string jirastatus { get; set; }
         public int dependencyFound { get; set; }
         public string depends { get; set; }
         public string linked_issues { get; set; }
       }

      public class DependencyManager
      {
          public List<Dependency> Dependencies { get; private set; }
          public DependencyManager()
          {
              this.Dependencies = new List<Dependency>();

          }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*ray 5

如果您索引到Dependencies集合中,则不会创建枚举器,您可以在修改集合时循环.如果新项目未附加到列表末尾或项目被删除,则此方法很容易引起麻烦.

for(int i = 0; i < mgr.Dependencies.Count; i++)
{
  var item = mgr.Dependecies[i];
  if (item.depends.Length > 0)
  {
      // code unchanged
  }
}
Run Code Online (Sandbox Code Playgroud)

一种安全的方法是使用一个Queue与从最初填入商品信息,mgr.Dependencies然后Enqueue要处理任何其他项目.

var toBeProcessed = new Queue<Dependency>(mgr.Dependencies);
while(toBeProcessed.Count > 0)
{
  var item = toBeProcessed.Dequeue();

  // loop

  // if a new dependency gets added that needs processing, just add it to the queue.
  toBeProcessed.Enqueue(newissue1);

}
Run Code Online (Sandbox Code Playgroud)