Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Linq - Delayed Execution

Tags:

c#

linq

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?

like image 876
parliament Avatar asked Jul 05 '12 20:07

parliament


1 Answers

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.

like image 103
Anders Abel Avatar answered Sep 21 '22 08:09

Anders Abel