Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting XmlNodeList to List<string>

Tags:

string

c#

xml

Is it possible to convert an XmlNodeList to a List<string> without declaring a new List<string>?

I am looking for a simple implementation for this:

System.Xml.XmlNodeList membersIdList = xmlDoc.SelectNodes("//SqlCheckBoxList/value");
List<string> memberNames = new List<string>();
foreach (System.Xml.XmlNode item in membersIdList)
{
    memberNames.Add(library.GetMemberName(int.Parse(item.InnerText)));
}
like image 277
Moran Monovich Avatar asked Feb 19 '14 05:02

Moran Monovich


1 Answers

Yes, it's possible using LINQ:

var memberNames = membersIdList.Cast<XmlNode>()
                               .Select(node => node.InnerText)
                               .Select(value => int.Parse(value))
                               .Select(id => library.GetMemberName(id))
                               .ToList();

Cast<XmlNode>() call is necessary, because XmlNodeList does not implement generic IEnumerable<T>, so you have to explicitly convert it to generic collection from non-generic IEnumerable.

And yes, you can merge all Select calls into one if you want:

var memberNames = membersIdList.Cast<XmlNode>()
                               .Select(x => library.GetMemberName(int.Parse(x.InnerText)))
                               .ToList();
like image 147
MarcinJuraszek Avatar answered Sep 28 '22 09:09

MarcinJuraszek