Hi trying to write a simple linq query from a tutorial I read. But i cannot seem to get it to work. I am trying to display both the address in the attached xml document, but can only display the first one. Can someone help me figure out why both aren’t being printed. Thank you very much
<?xml version="1.0" encoding="utf-8" ?>
<Emails>
<Email group="FooBar">
<Subject>Test subject</Subject>
<Content>Test Content</Content>
<EmailTo>
<Address>foo@bar.com</Address>
<Address>bar@foo.com</Address>
</EmailTo>
</Email>
</Emails>
Dim steve = (From email In emailList.Descendants("Email") _
Where (email.Attribute("group").Value.Equals("FooBar")) _
Select content = email.Element("EmailTo").Descendants("Address")).ToList()
If Not steve Is Nothing Then
For Each addr In steve
Console.WriteLine(addr.Value)
Next
Console.ReadLine()
End If
Your current query returns a
List<IEnumerable<XElement>>. That means you need two nestedforeachloops: one to loop over the list, and another to loop over the content of theIEnumerable<XElement>.Instead, you could update your LINQ query to use the
Enumerable.SelectManymethod and get to the addresses directly. In query format aSelectManyis represented by using a secondfromclause to indicate a subquery. This would resemble the following:Also, the
ToListisn’t needed if you only want to iterate over the results and don’t intend to use the result as a list for other purposes.EDIT: to explain how this query works let’s break it down in 2 parts:
First:
This queries for all
<Email>nodes and only matches the ones that have a group attribute value of “FooBar”.Second:
This is a subquery that continues where the first part (above) ended. It essentially is a way to further query the results of the original query. Here we query for all
<Address>nodes and, finally, select theirValuefor the inner text of the nodes. The reason we need to do this is becauseDescendants("Address")returns aIEnumerable<XElement>containing all “Address” elements. We need to perform an additional query (orforeach) to iterate over those values and extract their values.Another way to illustrate this is by breaking it down in 2 queries:
Notice the use of
SelectManyinquery2. TheSelectinquery2is that additional effort to loop over theIEnumerablethat I mentioned earlier. The original query is clearer than query1/query2, but I wrote them just to clarify the point.