Use a query with LINQ to XML

advertisements

I've this LINQ to XML request which retrieve all songs by artist 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();

When I'm trying to add the result in my ListBox like this :

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

I got this error :

error CS0030: Cannot convert type 'System.Collections.Generic.List' to 'string'

How to add properly my result in my ListBox ? Thanks for your help.


Because of your use of ToList() you're returning an enumerable of lists.

When you try to iterate over the enumerable collection your code tries to convert a list to a char which it cannot do.

Change your code to:

  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

If you don't want to make use of the lazy loading feature of an IEnumerable you can convert the whole result set to a list.