【问题标题】:Convert IEnumerable<XElement> to XElement将 IEnumerable<XElement> 转换为 XElement
【发布时间】:2010-08-27 18:41:06
【问题描述】:

我的查询的返回类型是IEnumerable&lt;XElement&gt;。如何将结果数据转换为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 ); 

【问题讨论】:

    标签: ienumerable xelement


    【解决方案1】:

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

    【讨论】:

    • 请注意,如果集合返回多于一个元素,则可以调用First()而不会产生异常。
    【解决方案2】:

    除了贾斯汀的回答之外,您可能希望允许返回 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 真的很重要。

    【讨论】:

    • 我在某处读到 .Any() 比 .Count() 更好用 ... 可能在 Eric Lippert 的博客上。
    【解决方案3】:

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

    resQ.ToList().ForEach(e => ...func... );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      相关资源
      最近更新 更多