2012-04-08 51 views
0

我有這個的LINQ to XML請求其通過藝術家ID檢索所有歌曲:使用請求與LINQ到XML

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(); 

當我嘗試添加的結果在我的列表框這樣的:

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

我得到這個錯誤:

錯誤CS0030:無法將類型 'System.Collections.Generic.List' 到 '字符串'

如何在我的ListBox中正確添加我的結果?謝謝你的幫助。

回答

3

由於您使用了ToList(),所以您返回了一個枚舉列表。

當您嘗試迭代可枚舉集合時,代碼會嘗試將列表轉換爲不能執行的char。

你的代碼更改爲:

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你的延遲加載功能可以將整個結果集列表。

+0

謝謝你的工作很好! – 2012-04-08 21:04:19

+0

另外請注意,使用's.Attribute(「path」).value'可能有點危險,除非你完全確定屬性'path'永遠不會在xml中丟失。如果你不確定使用'(string)s.Attribute(「path」)',它將返回string.Empty,如果該屬性在xml中缺失。 [請參閱MSDN的進一步解釋](http://msdn.microsoft.com/en-us/library/system.xml.linq.xattribute.value.aspx) – Hauge 2012-04-08 21:13:27

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).ToList(); 

或運送這麼在需要時查詢結果進行評估。