【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<string>' [duplicate]无法将类型“System.Collections.Generic.List<AnonymousType#1>”隐式转换为“System.Collections.Generic.List<string>”[重复]
【发布时间】:2014-05-03 21:40:10
【问题描述】:

我收到以下错误

Cannot implicitly convert type
'System.Collections.Generic.List<AnonymousType#1>' to
'System.Collections.Generic.List<string>'

我尝试阅读有关堆栈溢出的类似问题,但没有找到解决方案。 我的代码如下

var head =     
    from key in doc.Descendants("Header").Descendants("Article")
    select new 
     {
       value = (key.Value == String.Empty ?
       from q in doc.Descendants("Header").Descendants("Article") select q.Value : from a in doc.Descendants("Header").Descendants("Article") 
      select a.Attribute("DefaultValue").Value)

    };
List<string> hsourceFields = head.ToList();

如果 xml 节点的值为空,我正在读取为该 xml 节点指定的默认值

<Header>      
<Article>News</Article>
<Article DefaultValue ="Sport"></Article>    
</Header>

我希望能够通过收到错误返回一个我无法返回的列表。

【问题讨论】:

  • 如果将 List 更改为 List 会怎样

标签: c# linq linq-to-xml


【解决方案1】:

看起来您的代码得到的是 List&lt;AnonType{value = List&lt;string&gt;}&gt; 而不是 List&lt;string&gt;

我想你想要这样的东西,它会从文章中选择文本,或者如果它是空的,它将采用 DefaultValue 属性的值。请注意,当没有文本和属性时,这不会处理。

var head =     
    from key in doc.Descendants("Header").Descendants("Article")
    select      
      string.IsNullOrEmpty(key.Value) ?
          key.Attribute("DefaultValue").Value :
          key.Value;
List<string> hsourceFields = head.ToList();

或者使用 xpath 和方法链的稍微简化的版本

var hsourceFields = doc.XPathSelectElements("/Header/Article")
     .Select (x => string.IsNullOrEmpty(x.Value) ?
        x.Attribute("DefaultValue").Value :
        x.Value).ToList() 

【讨论】:

    【解决方案2】:

    如果您阅读错误,它会准确地告诉您问题所在。您想要一个字符串列表,但是您有一个匿名对象列表。而是使用

    var hSouceFields = head.ToList()
    

    【讨论】:

    • 我试过这个,上面是我得到的打印屏幕。如果这样做,我不会收到调试错误,但列表实际上并没有填充值。我想我需要一些我想念的演员或某事。
    【解决方案3】:

    我将读取 xml 节点的方式更改为

    var head = (from k in doc.Descendants("Header")
                select k).ToList();
    
    List<String> hsourceFields = new List<string>();
    
     foreach (var t in head.Descendants("Article"))
     {
         if (t.Attribute("DefaultValue") != null)
          {
              hsourceFields.Add(t.Attribute("DefaultValue").Value);
          }
          else
               hsourceFields.Add(t.Value);
    } 
    

    但我并不为我的解决方案感到自豪。

    【讨论】:

    • from k in doc.Descendants("Header") select k 可以简化为 doc.Descendants("Header")。而ToList() 在这里是不必要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多