Cante Ibanez
Cante Ibanez

Reputation: 321

LINQ Refactoring

I refactored my foreach loop from this before:

foreach (KeyValuePair[string, string] param in paramsList)
{
    XmlElement mainNode = xmlDoc.CreateElement("parameter");
    mainNode.SetAttribute("name", param.Key);
    mainNode.SetAttribute("value", param.Value);
    rootNode.AppendChild(mainNode);
}

to this, using LINQ:

XmlElement mainNode = xmlDoc.CreateElement("parameter");
var selected = paramsList.AsEnumerable().Select(param => param).ToList();
selected.ForEach(x => (mainNode.SetAttribute("name", x.Key)));
selected.ForEach(x => (mainNode.SetAttribute("value", x.Value)));
rootNode.AppendChild(mainNode);

However, i know the section below can still be refactored into a single loop but i dont know how. please enlighten me.

selected.ForEach(x => (mainNode.SetAttribute("name", x.Key)));
selected.ForEach(x => (mainNode.SetAttribute("value", x.Value)));

Upvotes: 1

Views: 221

Answers (3)

Joel Mueller
Joel Mueller

Reputation: 28765

Any chance you could switch from XmlDocument to XDocument? LINQ to XML integrates much better with LINQ, as you might expect.

var nodes = from pair in paramsList
            select new XElement("parameter",
                                new XAttribute("name", pair.Key),
                                new XAttribute("value", pair.Value));

And that's it, except for adding the nodes to the document, or passing them into an XDocument constructor or something.

Edit: To clarify, your question is tagged "linqtoxml", but LINQ to XML implies a specific set of classes in the System.Xml.Linq namespace, such as XDocument, XElement, and XAttribute. Your sample code isn't using any actual LINQ to XML classes, and I'm suggesting that if you want to use LINQ to build your XML, the actual LINQ to XML classes would serve you better than XmlDocument and friends.

Upvotes: 0

bruno conde
bruno conde

Reputation: 48265

I think you can achieve the same results with:

        paramsList.ToList().ForEach( e => {
            XmlElement mainNode = xmlDoc.CreateElement("parameter");
            mainNode.SetAttribute("name", e.Key);
            mainNode.SetAttribute("value", e.Value);
            rootNode.AppendChild(mainNode);
        });

but, in this case, I would choose a simple foreach:

        foreach (var e in paramsList)
        {
            XmlElement mainNode = xmlDoc.CreateElement("parameter");
            mainNode.SetAttribute("name", e.Key);
            mainNode.SetAttribute("value", e.Value);
            rootNode.AppendChild(mainNode);
        }

Upvotes: 3

John Boker
John Boker

Reputation: 83709

maybe something like this

selected.ForEach(x => 
          { 
             mainNode.SetAttribute("name", x.Key);
             mainNode.SetAttribute("value", x.Value);
          });

Upvotes: 2

Related Questions