3

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

3 回答 3

8

只要您的查询只返回一个结果,您就可以在结果上调用 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.

于 2010-08-27T18:42:46.193 回答
1

除了贾斯汀的回答,您可能希望允许返回 0 个元素或其他一些条件。

在这种情况下,只需执行以下操作:

IEnumerable<XElement> resQ = docElmnt.Descendents(xmlns + Constants.T_ROOT)
                   .Where(x => x.Attribute(Constants.T_ID).Value == "testid");
if(resQ.Count() == 0) {
  //handle no elements returned
} else if(resQ.Count() > 1) {
  //handle more than 1 elements returned
} else {
  XElement single = resQ.Single();
}

大多数时候,我发现最好不要抛出错误——除非准确返回 1 非常重要。

于 2010-08-27T18:55:03.117 回答
1

您可以遍历查询中的每个元素,然后使用您的枚举器调用该方法。

resQ.ToList().ForEach(e => ...func... );
于 2010-08-27T18:44:52.557 回答