This is surely a simple question and because I am too tired I don't see the answer myself, but my question is:
I have a for
loop, and in it a List<T>.Add()
, so that at each turn of the loop, it adds something to the list. But I checked and I see that at each turn, the adding adds the right element, but changes every other element of the list to the new one ! Would you know what could cause this? Here is my code:
private static List<Niveau> computeNiveaux(int[,] tri) {
List<Lot> lotsNiveau = new List<Lot>();
List<Niveau> niveaux = new List<Niveau>();
Lot lot;
bool isNiveau = false;
for (int row = 0; row < tri.GetLength(0); row++)
{
for (int column = 0; column < tri.GetLength(1); column++)
{
if (tri[row, column] == 1) {
lot = lots.ElementAt(column);
lotsNiveau.Add(lot);
isNiveau = true;
}
}
if (isNiveau)
{
Niveau niv = new Niveau(lotsNiveau.First().niveau, lotsNiveau.First().etage, lotsNiveau);
niveaux.Add(niv);
lotsNiveau.Clear();
isNiveau = false;
}
return niveaux;
}
lots
is a class variable (don't know what is the right name in english ^^')List<Lot>
A
Niveau
is :public class Niveau { public int numero; public string etage; public List<Lot> lots; public Niveau(int numero, string etage, List<Lot> lots) { this.numero = numero; this.etage = etage; this.lots = lots; } }
What I get for example when I want to see what are every
niveaux.ElementAt(i).lots.Count
(for i=0,...,niveaux.Count) :16 16 16 ...
Even if I know that in the first turn of the loop it was 7, then 4, then 10, etc. and the last turn is 16. (that's not really clear, I hope that you understand x') )At the next step of the loop, if the value added is for example
23
,niveaux
will become :23 23 23 23 ...
If you need any more information, tell me !
Sorry for my english ! :(