Robert J.
Robert J.

Reputation: 2701

LINQ retains unwanted data binding

Let's make a variable named i_Changes of type List<List<int>> which has the following values:

[1] = 1,2
[2] = 3,4,6
[3] = 4,8,15

This Variable is stored in a class myClass which looks like this:

Public Class myClass
{
    public DateTime selectedDate {get; set}
    public List<List<int>> i_Changes {get;set;}
}

Now we have another variable named i_Holder of type List<List<List<int>>> which is supposed to hold values of i_Changes (that means after every iteration I want to store exact numbers from i_Changes so that later (after process) I can show them all to user in a Grid.

What I do after every iteration, to store new variable is the following:

i_Holder.Add(myClass.Select(n=>n.i_Changes).ToList();

I found out that when I add items to my list like this, they keep binding with the original i_Changes, which means that after every iteration (when values under i_Changes change), all values under i_Holder change accordingly -> that means I have list of n items with exact same values such as current i_Changes.

How can I solve this problem?

Also, if you believe that List<List<List<int>>> is not a good idea, please feel free to correct me, as it was the only thing what I could think of.

Thank you

EDIT: I found out that when I create new List<List<int>> and manually copy each values to that list, then binding is lost; however I believe it is not the best thing to do (create new List after every iteration). Is there any better way to do this?

Upvotes: 1

Views: 90

Answers (2)

Baldrick
Baldrick

Reputation: 11840

You are holding a list of references to the same object, so when the object changes, you will see that change in every item in your list.

You need to create a new list containing the desired values each time, like this:

i_Holder.Add(myClass
    .Select(n => n.i_Changes.Select(j => new List<int>(j)).ToList()).ToList());

Upvotes: 2

Alex Art.
Alex Art.

Reputation: 8781

In C# lists are passed by reference so i think this is the reason you getting this issue. in order to avoid this you have to do deep copy of your lists, prior to adding them.

You can read about deep clone of the lists here

Upvotes: 1

Related Questions