簡體   English   中英

使用 LINQ 至 XML 的請求

[英]Use a request with LINQ to XML

我有這個 LINQ 到 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”轉換為“字符串”

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

由於您使用了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 的延遲加載功能,您可以將整個結果集轉換為列表。

您應該在整個查詢中使用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();

或發送它,以便在需要時評估查詢結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM