【问题标题】:Use a request with LINQ to XML使用带有 LINQ to XML 的请求
【发布时间】:2012-04-08 20:57:15
【问题描述】:

我有这个 LINQ to XML 请求,它按艺术家 ID 检索所有歌曲:

  var query = from c in loaded.Descendants("artist")
                    where c.Attribute("Id").Value.Equals("1")
                    from s in c.Descendants("song")
                    select s.Attribute("path").Value.ToList();

当我尝试将结果添加到我的 ListBox 中时:

foreach (string track in query)
        {
            myList.Items.Add(track);
        }

我收到了这个错误:

错误 CS0030:无法将类型“System.Collections.Generic.List”转换为“字符串”

如何在我的 ListBox 中正确添加我的结果?感谢您的帮助。

【问题讨论】:

    标签: c# wpf linq-to-xml


    【解决方案1】:

    由于您使用了ToList(),您将返回一个可枚举的列表。

    当您尝试遍历可枚举集合时,您的代码会尝试将列表转换为无法执行的字符。

    将您的代码更改为:

      var query = from c in loaded.Descendants("artist")
                        where c.Attribute("Id").Value.Equals("1")
                        from s in c.Descendants("song")
                        select s.Attribute("path").Value
    

    如果您不想使用 IEnumerable 的延迟加载功能,您可以将整个结果集转换为列表。

    【讨论】:

    • 另外请注意,使用s.Attribute("path").Value 可能有点危险,除非您绝对确定属性path 永远不会在xml 中丢失。如果您不确定使用(string)s.Attribute("path"),如果xml 中缺少该属性,它将返回string.Empty。 See MSDN for further explanation
    【解决方案2】:

    您应该在整个查询中使用ToList(),而不仅仅是“路径”属性值:

    var query = (from c in loaded.Descendants("artist")
                        where c.Attribute("Id").Value.Equals("1")
                        from s in c.Descendants("song")
                        select s.Attribute("path").Value).ToList();
    

    或发送它,以便在需要时评估查询结果。

    【讨论】:

      猜你喜欢
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      相关资源
      最近更新 更多