c# - 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']");
解决方案
FindIndex
期望 aPredicate<XElement>
不是XElement
.
这是一个谓词,您可以使用它来查找您要查找的元素:
int myIndexCase1 = myList.FindIndex(element => element.Name == "groupA" &&
element.Attribute("Name").Value == "blue");
推荐阅读
- web-scraping - 我正在尝试使用 IMPORTXML 将产品信息从 Keepa 提取到谷歌表中
- css - Mediawiki - 脚本错误:第 1 行的 Lua 错误:“/”附近出现意外符号
- nativescript - Nativescript-Vue 移除 iOS ListView 点击颜色
- database - 如何使用 VelocyPack (VPack) 在 ArangoDB 中存储图像?
- excel - 如何从数组中填充列?
- makefile - 在 Makefile $(info ...) 中使用制表符
- r - 将存储在列表中的数据帧分组为单独的新数据帧
- c - 类似于 memmove() 的结构赋值可以重叠还是类似于 memcpy() 的结构赋值?
- ssis - SSIS - 包级连接(连接 A)在所有包中具有相同的 {ID}。在哪里配置呢?
- tomcat - Fedora29 上的 Tomcat9:webapps 上的 403