-1

Here is my code:

public static int getUnidades(List<int> lista)
{
    string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlConnection SQLCon = new SqlConnection(conString);
    string SQLCom = "Select UnidadesCliente FROM Cliente WHERE @id = IdCliente";
    SqlCommand cmd = new SqlCommand(SQLCom, SQLCon);

    List<int> listaUnidades = lista;
    int t = 0;
    foreach(int i in lista)
    {
        cmd.Parameters.AddWithValue("@id", Convert.ToString(i));

        SQLCon.Open();
        listaUnidades[t] = Convert.ToInt32(cmd.ExecuteScalar());
        SQLCon.Close();
        t++;
    }

    int total = 0;
    foreach(int i in listaUnidades)
    {
        total = total + i;
    }

    return total;
}

I'm getting an InvalidOperationException in the foreach(int i in lista) loop, saying "collection was modified, enumeration operation may not execute". Now, I don't believe that I'm modifying the collection, so what's wrong?

AceBunny
  • 51
  • 1
  • 7
  • 1
    Possible duplicate of [Collection was modified; enumeration operation may not execute](http://stackoverflow.com/questions/604831/collection-was-modified-enumeration-operation-may-not-execute) – Rob Dec 02 '15 at 01:10

1 Answers1

1

I don't believe that I'm modifying the collection

You are, List<T> is a reference type and both listaUnidades and lista point to the same instance, so at listaUnidades[t] = you're modifying the same collection that you're iterating over.

Just let listaUnidades be a new List<int> and call Add() instead of using the indexer.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272