C#集合已修改;枚举操作可能无法执行

本文关键字:执行 操作 枚举 集合 修改 | 更新日期: 2023-09-27 17:58:03

可能重复:
集合已修改;枚举操作可能无法执行

你好,

我正在创建一个项目评估程序,并得到以下错误:C#集合被修改;枚举操作可能无法执行。

它与使用此相关:我最初在全球范围内宣布这一决定:

Dictionary<int, int> rankings = new Dictionary<int, int>();

包含此字典的下一个方法执行以下操作:

private void getFirstEstimation()
{
    List<int> array = new List<int>();
    string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
    MySqlConnection connection = new MySqlConnection(strConnection);
    MySqlCommand command = connection.CreateCommand();
    MySqlDataReader reader;
    command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers;
    connection.Open();
    reader = command.ExecuteReader();
    while (reader.Read())
    {
        array.Add(Convert.ToInt32(reader["idprojects"].ToString()));
    }
    foreach (int i in array)
    {
        rankings[i] = 15;
    }
    connection.Close();
}

我在这里第二次称之为

private void getSecondEstimation()
{
    Dictionary<int, string> sqltext = new Dictionary<int, string>();
    Dictionary<int, int> valueForSql = new Dictionary<int, int>();
    Dictionary<int, int> weightings = new Dictionary<int, int>();
    sqltext.Add(1, "project_type");
    valueForSql.Add(1, projectType);
    weightings.Add(1, 10);
    sqltext.Add(2, "application_domain");
    valueForSql.Add(2, applicationDomain);
    weightings.Add(2, 8);
    sqltext.Add(3, "organisation_size");
    valueForSql.Add(3, organizationSize);
    weightings.Add(3, 8);
    sqltext.Add(4, "no_of_locations");
    valueForSql.Add(4, noOfLocations);
    weightings.Add(4, 7);
    sqltext.Add(5, "development_process");
    valueForSql.Add(5, developmentProcess);
    weightings.Add(5, 6);
    sqltext.Add(6, "rules_engine");
    valueForSql.Add(6, rulesEngine);
    weightings.Add(6, 5);
    sqltext.Add(7, "middleware");
    valueForSql.Add(7, middleware);
    weightings.Add(7, 4);
    sqltext.Add(8, "location_of_development");
    valueForSql.Add(8, locationOfDevelopment);
    weightings.Add(8, 3);
    sqltext.Add(9, "programming_language");
    valueForSql.Add(9, programmingLanguage);
    weightings.Add(9, 3);
    sqltext.Add(10, "development_environment");
    valueForSql.Add(10, developmentEnvironment);
    weightings.Add(10, 3);
    sqltext.Add(11, "backend");
    valueForSql.Add(11, backend);
    weightings.Add(11, 3);
    sqltext.Add(12, "webserver");
    valueForSql.Add(12, webServer);
    weightings.Add(12, 3);
    List<int> array = new List<int>();
    string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
    MySqlConnection connection = new MySqlConnection(strConnection);
    MySqlCommand command = connection.CreateCommand();
    MySqlDataReader reader;
    for (int i = 1; i <= 12; i++)
    {
        command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE " + sqltext[i] + " = " + valueForSql[i];
        connection.Open();
        //int testInt;
        reader = command.ExecuteReader();
        while (reader.Read())
        {
            array.Add(Convert.ToInt32(reader["idprojects"].ToString()));
        }
        foreach (int a in array)
        {
            if (!rankings.ContainsKey(a))
            {
                rankings[a] = 0;
            }
            rankings[a] = rankings[a] + weightings[i];
        }
        connection.Close();
    }       
}

问题出现在代码的这个区域:

private void getThirdEstimation()
{
    ArrayList tempModuleHolder;
    string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
    MySqlConnection connection = new MySqlConnection(strConnection);
    MySqlCommand command = connection.CreateCommand();
    MySqlDataReader reader;
    int similarModules;
    foreach (KeyValuePair<int, int> kvp in rankings)
    {
        similarModules = 0;
        tempModuleHolder = new ArrayList();
        command.CommandText = "SELECT id_modules FROM `test`.`modules_in_project` WHERE id_project = " + kvp.Key;
        connection.Open();
        reader = command.ExecuteReader();
        while (reader.Read())
        {
            tempModuleHolder.Add(Convert.ToInt32(reader["id_modules"].ToString()));
        }
        foreach (int i in tempModuleHolder)
        {
            if(modules.Contains(i))
            {
                similarModules++;
            }
        }
        if((double)(similarModules/modules.Count)>0.6)
        {
            //kvp.Value = kvp.Value + 4;
            rankings[kvp.Key] = rankings[kvp.Key] + 4;
        }
        connection.Close();
    }
}

任何关于问题所在的帮助都将非常感谢

C#集合已修改;枚举操作可能无法执行

使用foreach迭代的任何集合在迭代过程中都不会被修改。

因此,当你在排名上运行foreach时,你不能修改它的元素,添加新的元素或删除任何元素。

错误告诉您问题的确切位置(在调试器中运行或读取堆栈跟踪将告诉您问题的准确位置):

C#集合已修改;枚举操作可能无法执行。

你的问题是循环

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

其中修改集合CCD_ 1。特别是,进攻线是

rankings[kvp.Key] = rankings[kvp.Key] + 4;

在进入循环之前,添加以下行:

var listOfRankingsToModify = new List<int>();

用替换有问题的行

listOfRankingsToModify.Add(kvp.Key);

在你退出循环之后

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

也就是说,记录需要进行的更改,并在不迭代需要修改的集合的情况下进行更改。

正如其他人所指出的,您正在修改正在迭代的集合,这就是导致错误的原因。违规代码如下:
foreach (KeyValuePair<int, int> kvp in rankings)
{
    .....
    if((double)(similarModules/modules.Count)>0.6)
    {
        rankings[kvp.Key] = rankings[kvp.Key] + 4;  // <--- This line is the problem
    }
    .....

从上面的代码中可能不明显的是Enumerator的来源。在几年前的一篇关于Eric Lippert的博客文章中,提供了一个foreach循环被编译器扩展为什么的例子。生成的代码看起来像:

{
    IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
                                                       // is where the Enumerator
                                                       // comes from.
    try
    { 
        int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
        while(e.MoveNext())
        {
            // loop code goes here
        }
    }
    finally
    { 
      if (e != null) ((IDisposable)e).Dispose();
    }
}

如果您在MSDN文档中查找IEnumerable(这是GetEnumerator()返回的内容),您将看到:

枚举器可用于读取集合中的数据,但不能用于修改基础集合

这让我们回到错误消息和其他答案的状态,即您正在修改基础集合。

我怀疑错误是由以下原因引起的:

foreach (KeyValuePair<int, int> kvp in rankings)

排名是一本字典,它是IEnumerable。通过在foreach循环中使用它,可以指定您希望以延迟的方式从字典中获得每个KeyValuePair。也就是说,在循环再次迭代之前,不会返回下一个KeyValuePair。

但你正在修改循环中的字典:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

这是不允许的。。。所以你得到了例外。

你可以简单地做这个

foreach (KeyValuePair<int, int> kvp in rankings.ToArray())

问题在于执行的位置

rankings[kvp.Key] = rankings[kvp.Key] + 4;

您不能在foreach循环中修改正在迭代的集合。foreach循环要求循环在迭代过程中是不可变的。

相反,使用一个标准的"for"循环,或者创建一个新的副本循环,并在更新原始循环时对其进行迭代。