首页 > 解决方案 > C# XElement 作为谓词<>

问题描述

将 XElement 添加到列表中时,我无法像通常使用字符串或 int 数据列表那样进行查找。请告知我必须在下面进行哪些更改才能使其作为 myIndexCase1 或 myIndexCase2 工作?

using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml;
using System.Text;

XElement x1 = new XElement("groupA", new XAttribute("Name","red"));
XElement x2 = new XElement("groupA", new XAttribute("Name","blue"));
XElement x3 = new XElement("groupA", new XAttribute("Name", "green"));
XElement x4 = new XElement("groupB", new XAttribute("Name", "white"));
XElement x5 = new XElement("groupB", new XAttribute("Name", "black"));

List<XElement> myList = new List<XElement>();
myList.Add(x1);
myList.Add(x2);
myList.Add(x3);
myList.Add(x4);
myList.Add(x5);

//We know x2 belongs to index = 1 but this syntax doesn't work ..it complains can not convert XElement to Predicates
int myIndexCase1 = myList.FindIndex(x2);

//And if I try this too also doesn't work
int myIndexCase2 = myList.FindIndex(s => x1.XPathSelectElements("group[@Name='blue']");

标签: c#

解决方案


FindIndex期望 aPredicate<XElement>不是XElement.

这是一个谓词,您可以使用它来查找您要查找的元素:

int myIndexCase1 = myList.FindIndex(element => element.Name == "groupA" &&
                                         element.Attribute("Name").Value == "blue");

推荐阅读