从 LINQ to XML 查询获取单个字符串
这是我想要做的:
string parseCode = from x in xml.Descendants("LogType")
where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
select x.Attribute("ParseCode").Value;
但这会产生错误:“无法将类型 'System.Collections.Generic.IEnumerable' 隐式转换为 'string'”
x 只有一个值.Attribute("ParseCode")
但它坚持返回类型 IEnumerable
。如何将该值提取到字符串中?
编辑:谢谢您的回复。这是对我有用的:
string parseCode = (from x in xml.Descendants("LogType")
where x.Attribute("ID").Value == (string) ddlHistoryLogDefinitions.SelectedValue
select (string) x.Attribute("ParseCode").Value).FirstOrDefault();
这个技巧将整个 linq 查询包装在 .FirstOrDefault() 之前的 () 中。
Here is what I want to do:
string parseCode = from x in xml.Descendants("LogType")
where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
select x.Attribute("ParseCode").Value;
But that gives error: "Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string'"
There will only be one value for x.Attribute("ParseCode")
but it insists on returning type IEnumerable<string>
. How can I extract that value into a string ?
EDIT: Thank you for your responses. Here is what worked for me:
string parseCode = (from x in xml.Descendants("LogType")
where x.Attribute("ID").Value == (string) ddlHistoryLogDefinitions.SelectedValue
select (string) x.Attribute("ParseCode").Value).FirstOrDefault();
This trick was wrapping the entire linq query in () before the .FirstOrDefault().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您知道只有一个结果,请使用
.Single
选择唯一的结果:使用
.SingleOrDefault
或.First
如果可能存在分别没有或超过一个。Use
.Single
to select the only result if you know there will be one and only one:Use
.SingleOrDefault
or.First
If there might be none or more then one respectively.您查询返回一个集合。如果您需要第一个找到的
LogType
节点,那么您可以执行以下操作:如果未找到元素,则返回
null
。You query returns a collection. If you need the first found
LogType
node, then you can do something like this:Will return
null
if no element found.