Home > Software design >  C# The same item is keep adding to list using Foreach loop
C# The same item is keep adding to list using Foreach loop

Time:07-27

I am trying to go through an xml document and per each node add some attribute values into a list using foreach loop. I am accessing the right part of xml document, but after each iteration of foreach loop, all the values are overwritten with new one. So in the end there is a List of all the same items.

IEnumerable<XElements> accesses = steps.Descendants("Access").Where(acc => acc.Attributes("Scope").First().Value == "GlobalVariable);
    foreach (XElement access in accesses)
    {
        IEnumerable<XElement> accessComponent = access.Descendants("Component").ToList();
        newGlobVar.DbName = accessComponent.First().Attribute("Name")?.Value;
        newGlobVar.TagName = accessComponent.ElementAt(1).First().Attribute("Name")?.Value;
      
    globalVariables.Add(newGlobVar);
    }
return globalVariables;

CodePudding user response:

You have only one instance of the newGlobVar variable and you change its properties. That's why also properties of added items do change. You have to create one new instance of the variable for each foreach loop.

  • Related