首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# XElement as a Predicate<>

C# XElement as a Predicate<>
EN

Stack Overflow用户
提问于 2021-02-19 18:28:53
回答 1查看 32关注 0票数 0

在将XElement添加到列表中时,我不能像通常使用字符串或整型数据列表那样执行查找。请建议我必须在下面做什么更改才能使其作为myIndexCase1或myIndexCase2工作?

代码语言:javascript
复制
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']");
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-19 18:34:07

FindIndex需要Predicate<XElement>,而不是XElement

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

代码语言:javascript
复制
int myIndexCase1 = myList.FindIndex(element => element.Name == "groupA" &&
                                         element.Attribute("Name").Value == "blue");
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66275835

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档