Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”_C#_Linq_Linq To Xml - Fatal编程技术网

C# 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”

C# 无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”,c#,linq,linq-to-xml,C#,Linq,Linq To Xml,我得到以下错误 Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#1>' to 'System.Collections.Generic.List<string>' 我试图阅读有关堆栈溢出的类似问题,但没有找到解决方案。 我的代码如下 var head = from key in doc.Descendants("Header").Descendan

我得到以下错误

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>
我希望能够返回一个列表,但由于错误,我无法返回该列表


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

var hSouceFields = head.ToList()

我将读取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);
} 

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

看起来您的代码得到的是列表而不是列表

我认为您需要这样的东西,它将从文章中选择文本,或者如果文本为空,它将采用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();

如果你把列表改成列表呢?我试过了,上面是我得到的打印屏幕。如果我这样做,我不会得到调试错误,但是列表实际上没有填充值。我想我需要一些演员或我缺少的东西。从doc.genderantsheader中的k选择k可以简化为doc.genderantsheader。这里不需要托利斯。
var hsourceFields = doc.XPathSelectElements("/Header/Article")
     .Select (x => string.IsNullOrEmpty(x.Value) ?
        x.Attribute("DefaultValue").Value :
        x.Value).ToList()