Skip to main content
 首页 » 编程设计

c#之如何遍历更改集合

2024年02月02日2652php

我有以下代码。

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

在此,我正在遍历 mgr.Dependencis 集合。此值在 newissue1.getChangeSet(jiraOps, jiraURL, token, username, password, projectKey, exportTargetPath, branch, svnOps, svnExePath, changesetDBFile, mgr); 中发生变化 所以对于这个方法的每一次调用,我的收藏值(value)都在增加。但这是第一次工作正常。但是在第二次迭代时它给出了异常

Collection was modified; enumeration operation may not execute.

我认为这个异常(exception)是为了改变集合。如何处理这种情况?

我的类定义如下。

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

请您参考如下方法:

如果您索引到 Dependencies 集合,则不会创建 Enumerator,您可以在修改集合时循环访问。如果新项目没有附加到列表末尾或项目被删除,这种方法很容易引起麻烦。

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

一种安全的方法是使用 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); 
 
}