[英]C# XElement as a Predicate<>
将 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']");
FindIndex
需要Predicate<XElement>
而不是XElement
。
这是一个谓词,您可以使用它来查找您要查找的元素:
int myIndexCase1 = myList.FindIndex(element => element.Name == "groupA" &&
element.Attribute("Name").Value == "blue");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.