0

Currently I have a class called Field:

public class Field
{
    public int Id { get; set; }
}

var listOfListOfFields = new List<List<Field>>();

var listOfFields = new List<Field>(){ new Field {id = 1}}; // in reality, data comes here.

for (int i = 0; i <= 2; i++)
{
var copyFirstList = listOfFields.ToList(); // to avoid reference thing, I still get same value
for(int j =0; j < copyFirstList.Count; j++)
{
 copyFirstList[j].Id = i;
}

listOfListOfFields.Add(copyFirstList);
}

The output in the listOfListOfFields contains 2 for all the lists in id. Please suggest.

Gauravsa
  • 6,330
  • 2
  • 21
  • 30

1 Answers1

4

Copying a list of references types gives you the same references to those reference types (nothing changed). For instance, if someone gave you a bucket of post-it-notes with phone numbers on them, and you tip them in to another bucket, you still have the same post-it-notes!

There are many ways to solve this problem. However, one way is to project using Select and recreating the objects

copyFirstList = listOfFields.Select(x => new Field() {Id = x.Id}).ToList():
TheGeneral
  • 79,002
  • 9
  • 103
  • 141