gpt4 book ai didi

ienumerable - 将 IEnumerable 转换为 XElement

转载 作者:行者123 更新时间:2023-12-01 08:40:39 27 4
gpt4 key购买 nike

我的查询返回类型是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/

27 4 0