-1

I have two ICollection lists fullList and displayList.

private void method()
{
    if(condition != null) {
        displayList.Clear();
        if(fullList.Count() > 0)
        {
            displayList.ClearAndAddRange(
                           fullList.Where(x=>x.conditionID == condition.conditionID));

        }
    }

}

The problem I'm currently facing is whenever I update some value in displayList, fullList gets also updated . Is this expected behaviour?

What is the best way to modify it so that they won´t share references in between?

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
SuicideSheep
  • 5,260
  • 19
  • 64
  • 117
  • 1
    `ICollection` does not have such method. Is it a custom implementation of some sort? Did you assign the same instance to the different variables by any chance? – Caramiriel Oct 07 '15 at 10:37
  • Use a projection with '.select(x => new {...})’. I can't code it without knowing what your collections contain. – Crowcoder Oct 07 '15 at 10:45

1 Answers1

1

This is indeed expected behaviour. Consider the following two lists:

var list1 = new[] { myObj1, myObj2 };
var list2 = list1;

list2[0].myProp = 3;

where myObj1 and myObj2 are instances of MyClass.

As list1 and list2 share the same references to the contained objects all modifications made to any of those items will be reflected in the other list also. When you want to avoid this behavioour you have to provide a deep-copy which will create an entriely new instance of your objects:

var list2 = list1.Select(x => new MyClass { ... });

For further information on deep cloning also see this post.

Community
  • 1
  • 1
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111