devopsEMK devopsEMK -4 years ago 210
C# Question

Use Parallel.ForEach with XmlNodeList in C#

I already done basic

foreach
loop with
XmlNodeList
as given bellow.

Sample XML File (books.xml)

XmlDocument doc = new XmlDocument();
doc.Load("books.xml");
XmlNodeList xnList = doc.SelectNodes("catalog/book");
foreach (XmlNode node in xnList)
{
Console.WriteLine(node["author"].InnerText);
}


How do I convert this loop into
Parallel.ForEach
?

I've try with this code.But it's didn't work.

Parallel.ForEach(xnList, (XmlNode node) =>
{
Console.WriteLine(node["author"].InnerText);
});


It's says Error 2


Argument 1: cannot convert from
System.Xml.XmlNodeList
to
System.Collections.Generic.IEnumerable<System.Xml.XmlNode>


Answer Source

XmlNodeList implements the non-generic IEnumerable. You'll need to cast it first in order to work with an IEnumerable<XmlNode>, as that is what Parallel.ForEach operates on:

Parallel.ForEach(xnList.Cast<XmlNode>(), (XmlNode node) =>
{
   Console.WriteLine(node["author"].InnerText);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download