Bra*_*gue 1 c# linq linq-to-xml
这是我想要做的:
string parseCode = from x in xml.Descendants("LogType")
where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
select x.Attribute("ParseCode").Value;
Run Code Online (Sandbox Code Playgroud)
但是这会产生错误:"无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'string'"
只有一个值,x.Attribute("ParseCode")但它坚持返回类型IEnumerable<string>.如何将该值提取到字符串中?
编辑:谢谢你的回复.这对我有用:
string parseCode = (from x in xml.Descendants("LogType")
where x.Attribute("ID").Value == (string) ddlHistoryLogDefinitions.SelectedValue
select (string) x.Attribute("ParseCode").Value).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
这个技巧是在.FirstOrDefault()之前将整个linq查询包装在()中.
使用.Single选择的唯一结果,如果你知道将有一个且只有一个:
string parseCode = (from x in xml.Descendants("LogType")
where x.Attribute("ID").Value == string)ddlHistoryLogDefinitions.SelectedValue
select x.Attribute("ParseCode").Value).Single();
Run Code Online (Sandbox Code Playgroud)
使用.SingleOrDefault或.First如果可能分别没有或多于一个.