简体   繁体   中英

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)));

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);
        }

maybe something like this

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM