ienumerable - 将 IEnumerable<XElement> 转换为 XElement

标签 ienumerable xelement

我的查询返回类型是IEnumerable<XElement> .如何将结果数据转换为 XElement类型?可能吗?有人可以帮助我理解这一点。

var resQ = from e in docElmnt.Descendants(xmlns + Constants.T_ROOT)
                             .Where(x => x.Attribute(Constants.T_ID).Value == "testid") 
           select e;

我必须将 resQ 作为参数传递给下面的函数。为此,我必须将 resQ 转换为 XElement 类型。

Database.usp_InsertTestNQuestions(tid, qId, qstn, ans, resQ ); 

最佳答案

只要您的查询只返回一个结果,您就可以在结果上调用 Single() 或 First()(另外,顶部不需要额外的查询语法):

// Use if there should be only one value.
// Will throw an Exception if there are no results or more than one.
var resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT)
                   .Single(x => x.Attribute(Constants.T_ID).Value == "testid");

// Use if there could be more than one result and you want the first.
// Will throw an Exception if there are no results.
var resQ = docElmnt.Descendents(xmlns + Contants.T_ROOT)
                   .First(x => x.Attribute(Constants.T_ID).Value == "testid");

如果你想处理查询没有返回结果而不抛出异常的情况,你可以使用 SingleOrDefault (如果你得到多个结果,它仍然会抛出异常)或FirstOrDefault.

关于ienumerable - 将 IEnumerable<XElement> 转换为 XElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3587164/

相关文章:

c# - 如何从c#中的xml字符串中获取特定值

ienumerable - 共/逆变? Tuple<string, IEnumerable<string>> 不满足 List<string>

c# - 将 XElement 转换为 XmlNode

c# - 访问 IEnumerable 清除内容

c# - 在 XML 中更新和添加新标签

c# - 如何使用 XElement 在标签之间添加值?

c# - ASP.NET 将 xml 字符串转换为字典

c# - 使用 Cast<T> 将 int[] 转换为 double[]?

c# - 编译为空的虚拟 IEnumerable<T>