0

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 ?

ChrisF
  • 134,786
  • 31
  • 255
  • 325
mukul nagpal
  • 93
  • 1
  • 12

1 Answers1

2

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();
    }
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325