Chris
Chris

Reputation: 3

C# Linq to XML Element.Remove Code Optimization

I've been using Linq to XML for a while but am far from an advanced user of it. And every once in a while I look at my code and go, "There has to be a more efficient way to do this", and so I'm looking to see if the world of StackOverflow might know of a way to improve the following code. What's being accomplished is the method is fed a simple List<string> that has a list of software that is to be removed from a systems record held in a XML file.

var xe = (from el in mainForm.xeSystemData.Elements("System")
              where el.Element("Name").Value == systemName
              select el.Element("SoftwareList"));

    foreach (string sw in softwareToRemove)
    {
        foreach (var v in xe.Elements("Software"))
        {
            if (v.Value.ToString() == sw)
            {
                v.Remove();
            }
        }
    }

Here is a snippet of the XML for reference:

<SoftwareList>
  <Software>IBM Client Access</Software>
  <Software>Adobe Acrobat Reader 10.1</Software>
</SoftwareList>

What I keep thinking is that there is a quicker way to utilize Linq to XML to remove selective elements without creating two foreach loops.

Upvotes: 0

Views: 112

Answers (2)

Shreya
Shreya

Reputation: 204

var xe = (from el in mainForm.xeSystemData.Elements("System")
          where el.Element("Name").Value == systemName
          select el.Element("SoftwareList"));

xe.Descendants("Software").Where(x => softwareToRemove.Contains(x.Value)).Remove();

You do not need to run any foreach loop, just add the above LINQ query and you will get the desired result. I have tested my query and it works exactly what you want

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160902

I'd probably do something like this:

var toRemove = new HashSet<string>(sofwareToRemove);

foreach(var item in xe.Elements("Software")
                      .Where(e => toRemove.Contains(e.Value))
{
   item.Remove();
}

This is not specific to Linq to XML though, just using a HashSet instead of a list, which reduces the overall effort from O(n^2) to O(n)

Upvotes: 2

Related Questions