LINQ refactoring

I refactored my foreach loop from this earlier:

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

      

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 that the section below can still be refactored into one loop, but I don’t know how. please enlighten me.

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

      

+1


source to share


3 answers


I think you can achieve the same results:

        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 one foreach

:

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

      

+3


source


maybe something like this



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

      

+2


source


Can I switch from XmlDocument to XDocument? LINQ to XML integrates better with LINQ, as you'd expect.

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

      

And that is, except for adding nodes to the document or passing them to the XDocument constructor or something.

Edit: To clarify, your question is labeled "linqtoxml", but LINQ to XML implies a specific set of classes in the System.Xml.Linq namespace such as XDocument, XElement, and XAttribute. Your code example does not use any real LINQ to XML classes, and I suggest that if you want to use LINQ to create your XML, the actual LINQ to XML classes will serve you better than XmlDocument and friends.

0


source







All Articles