Search code examples
c#xelement

Copying one Xelement in to another and then Manipulating the newer one is affecting the older also


I am making one Xelement from another.

But when I am manipulating the new Xelement, it is changing the earlier one also.

private bool myFunction(List<XElement> jobList)
{
   List<XElement> tempJobList = new List<XElement>(jobList);
   foreach (XElement elements in tempJobList)
  {
    elements.Attribute("someattribute").Remove();
  }
}

Now here , after this if when I will check "jobList" , its attribute is also getting removed. Any suggestions ?


Solution

  • All you are doing is adding the same element from the original jobList to the new tempJobList so both lists are pointing at the same dataset. This means that when you manipulate an element you are changing it on both lists.

    If you really want a separate object then you need to clone the element before adding it to the temporary list.

    private bool myFunction(List<XElement> jobList)
    {
        List<XElement> tempJobList = new List<XElement>();
        foreach (var element in jobList)
        {
            // Take a copy
            var tempElement = new XElement(element);
            tempJobList.Add(tempElement);
        }
    
        foreach (XElement elements in tempJobList)
        {
            elements.Attribute("someattribute").Remove();
        }
    }