Search code examples
c#collectionsfilewriterstreamwriter.write

Write 2D List to File Error: System.InvalidOperationException:


I have a List double [,] array. When i try to below code c# to write 2d double list array to file i got error. "System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'"

public void Write(List<double[,]> arrays, string filepath)
        {
            using (StreamWriter sw = new StreamWriter(filepath))
            {
                foreach (double[,] array in arrays)
                {
                    int i = 0;
                    while (i < array.GetLength(0))
                    {
                        string line = "";
                        int o = 0;
                        while (o < array.GetLength(1))
                        {
                            line = line + array[i, o];
                            if (o + 1 < array.GetLength(1))
                            {
                                line = line + " ";
                            }
                            o++;
                        }
                        sw.WriteLine(line);
                        i++;
                    }
                }
            }
        }

Thanks.


Solution

  • The code works fine to me, by the error, it looks like you are modifying the collection somewhere else where write() function hasn't finished yet

    more on that you can find here