【问题标题】:Cannot implicitly convert type 'IEnumerable<XElement>' to 'bool'无法将类型“IEnumerable<XElement>”隐式转换为“bool”
【发布时间】:2012-06-14 12:07:02
【问题描述】:

我想找到Xelement的attribute.value,哪个孩子有一个具体的attribute.value。

string fatherName =  xmlNX.Descendants("Assembly")
                           .Where(child => child.Descendants("Component")
                               .Where(name => name.Attribute("name").Value==item))
                           .Select(el => (string)el.Attribute("name").Value); 

我怎样才能得到attribute.value?它说什么是布尔值?

已编辑 最初我有以下 XML:

<Assembly name="1">
  <Assembly name="44" />
  <Assembly name="3">
     <Component name="2" />
  </Assembly>
  </Assembly>

我需要获取其子 (XElement) 具有特定属性的属性值。 在这个例子中,我会得到字符串“3”,因为我正在搜索子元素的父元素 which attribute.value == "2"

【问题讨论】:

    标签: c# .net linq compiler-errors linq-to-xml


    【解决方案1】:

    因为嵌套的Where 子句的编写方式。

    内部子句是

    child.Descendants("Component").Where(name => name.Attribute("name").Value==item)
    

    这个表达式有一个IEnumerable&lt;XElement&gt;类型的结果,所以外面的子句是

    .Where(child => /* an IEnumerable<XElement> */)
    

    但是 Where 需要一个 Func&lt;XElement, bool&gt; 类型的参数,在这里你最终会传入一个 Func&lt;XElement, IEnumerable&lt;XElement&gt;&gt; - 因此会出现错误。

    我没有提供更正的版本,因为您的意图从给定的代码中根本不清楚,请相应地更新问题。

    更新:

    看起来你想要这样的东西:

    xmlNX.Descendants("Assembly")
         // filter assemblies down to those that have a matching component
         .Where(asm => asm.Children("Component")
                         .Any(c => c.name.Attribute("name").Value==item))
         // select each matching assembly's name
         .Select(asm => (string)asm.Attribute("name").Value)
         // and get the first result, or null if the search was unsuccessful
         .FirstOrDefault();
    

    【讨论】:

      【解决方案2】:

      我想你想要

      string fatherName =  xmlNX.Descendants("Assembly")
                                 .Where(child => child.Elements("Component").Any(c => (string)c.Attribute("name") == item))
                                 .Select(el => (string)el.Attribute("name")).FirstOrDefault();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多