我的查询的返回类型是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 ); 发布于 2010-08-28 02:42:46
只要您的查询只返回一个结果,您就可以对结果调用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-28 02:44:53
您可以迭代查询中的每个元素,然后使用枚举器调用该方法。
resQ.ToList().ForEach(e => ...func... );发布于 2010-08-28 02:55:03
除了Justin的回答之外,您可能希望允许返回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个非常重要。
https://stackoverflow.com/questions/3587164
复制相似问题