parliament
parliament

Reputation: 22914

C# Linq - Delayed Execution

If I build a query say:

(the query is build using XDocument class from System.Xml.Linq)

var elements = from e in calendarDocument.Root.Elements("elementName") select e;

and then I call elements.Last() SEVERAL times. Will each call return the most up to date Last() element?

For example if I do

elements.Last().AddAfterSelf(new XElement("elementName", "someValue1"));
elements.Last().AddAfterSelf(new XElement("elementName", "someValue2"));
elements.Last().AddAfterSelf(new XElement("elementName", "someValue3"));
elements.Last().AddAfterSelf(new XElement("elementName", "someValue4"));

Is it actually getting the latest element each time and added a new one to the end or is elements.Last() the same element each time?

Upvotes: 10

Views: 1514

Answers (1)

Anders Abel
Anders Abel

Reputation: 69260

Yes, linq queries are lazy evaluated. It's not until you call Last() that the query will be executed. In this case it will get the most up to date last element each time.

I think that this actually is the first time I've seen a proper use of calling Last() (or any other operator that executes the query) several times. When people do it, it is usually by mistake causing bad performance.

I think that the linq-to-xml library is smart enough to get good performance for your query, but I wouldn't trust it without trying.

Upvotes: 11

Related Questions