1

In the MSDN documentation for the XElement.Elements(XName) method, there is the following example:

XElement xmlTree = new XElement("Root",
    new XElement("Type1", 1),
    new XElement("Type1", 2),
    new XElement("Type2", 3),
    new XElement("Type2", 4),
    new XElement("Type2", 5)
);

IEnumerable<XElement> elements =
    from el in xmlTree.Elements("Type2")
    select el;
foreach (XElement el in elements)
    Console.WriteLine(el);

Is there a difference between that and the following, which produces the same result?

foreach (XElement el in xmlTree.Elements("Type2"))
    Console.WriteLine(el);

Is there a reason the query operators were used here?

jukbot
  • 113
  • 4
  • 1
    Possibly related: http://stackoverflow.com/questions/27424193/what-is-the-purpose-of-using-selectx-x-in-a-batch-method – lc. Dec 19 '14 at 05:25

2 Answers2

1

In this case there is no difference between the two. I believe the documentation was simply trying to demonstrate the ability to query an XML structure. This kind of query syntax allows for much more detailed and expressive results.

If you're concerned about the possibility of what may look like multiple enumeration of the values you can rest easy because IEnumerable is evaluated when it is consumed (the for each loop) so there's not really any extra work happening behind the scenes.

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
0

This post actually has some good answers about the difference between Linq and Foreach. The best answer also included a blog post which is very useful: https://codereview.stackexchange.com/questions/14197/is-the-linq-version-faster-than-the-foreach-one

Community
  • 1
  • 1
Hozikimaru
  • 1,144
  • 1
  • 9
  • 20