Converting XmlNodeList to List

2020-07-02 12:03发布

Is it possible to convert an XmlNodeList to List? without declaring a new List 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)));
    }

标签: c# xml string
2条回答
家丑人穷心不美
2楼-- · 2020-07-02 12:28

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();
查看更多
smile是对你的礼貌
3楼-- · 2020-07-02 12:31

Why don't you use LINQ to XML ?

List<string> memberNames = XDocument.Load("path")
                           .XPathSelectElements("//SqlCheckBoxList/value")
                           .Select(x => library.GetMemberName((int)x))
                           .ToList();
查看更多
登录 后发表回答