c#linq到xml错误:无法隐式转换类型
我得到以下错误: 无法将类型System.Collections.Generic.IEnumerable隐式转换为System.Xml.Linq.XElement。存在显式转换(是否缺少转换? 我有一个XML文件,看起来像:c#linq到xml错误:无法隐式转换类型,c#,xml,linq,C#,Xml,Linq,我得到以下错误: 无法将类型System.Collections.Generic.IEnumerable隐式转换为System.Xml.Linq.XElement。存在显式转换(是否缺少转换? 我有一个XML文件,看起来像: <Users xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/"> <User ID="91" Name="Jane Smith" LoginName="domain1\jsmi
<Users xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">
<User ID="91" Name="Jane Smith" LoginName="domain1\jsmith" />
<User ID="814" Name="Brad Jones" LoginName="domain1\bjones" />
<User ID="1252" Name="Charles Johnson" LoginName="domain2\cjohnson" />
</Users>
您需要将最后一行中的
.Where
更改为.SingleOrDefault您需要将最后一行中的.Where
更改为。SingleOrDefault。Where()
将返回IEnumerable
,即使其中只有一项。如果您只希望返回一个项目,则可以在可枚举的上调用.First()
或.FirstOrDefault()
。其中()
将返回一个IEnumerable
,即使其中只有一个项目。如果您只希望返回一个项目,则可以在可枚举项上调用.First()
或.FirstOrDefault()
XElement userNode = siteUserData.Descendants("User")
.Where(n => n.Attribute("ID").Value.Equals("12").FirstOrDefault();
或
您还可以使用Single()
和First()
,具体取决于您希望返回的严格程度。使用
XElement userNode = siteUserData.Descendants("User")
.Where(n => n.Attribute("ID").Value.Equals("12").FirstOrDefault();
或
您还可以使用Single()
和First()
,具体取决于您希望返回的严格程度。您需要告诉linq您只需要一个节点
var userNode = siteUserData.Descendants("User")
.FirstOrDefault(n => n.Attribute("ID").Value.Equals("12"));
您需要告诉linq您只需要一个节点
var userNode = siteUserData.Descendants("User")
.FirstOrDefault(n => n.Attribute("ID").Value.Equals("12"));