Is there a way to pass a list of strings to a linq to xml query or do I need to specify each filter separately? I want to count the number of elements that have the same name as the strings in a list.
Here's code that obviously doesn't work but gives you an idea what I'm looking to do:
XDocument doc = XDocument.Load(pathToXmlFile);
List<string> myList = new List<string> { "node1", "node2" };
int count = doc.Descendants().Where(x => x.Element(myList)).Count();
Obviously, x.Element can't take a list of strings, but is there another way to do this other than typing out individual x.Element("node1"), x.Element("node2"), etc?
Edit:
I wasn't able to get it working with implicit conversion to XName, so this is how I did it:
int count = doc.Descendants().Where(x => myList.Any(n => x.Name.ToString() == n)).Count();
The key to this was the Any method.
这将按您期望的那样工作:
int count = doc.Descendants().Where(x => myList.Any(n => x.Element(n))).Count();
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.