Linq deferred execution with local values

I experimented with Linq to see what it can do - and I really love it so far :)

I wrote some queries for the algorithm, but I did not get the expected results ... The enumeration always returned empty:

case # 1

List<some_object> next = new List<some_object>(); some_object current = null; var valid_next_links = from candidate in next where (current.toTime + TimeSpan.FromMinutes(5) <= candidate.fromTime) orderby candidate.fromTime select candidate; current = something; next = some_list_of_things; foreach (some_object l in valid_next_links) { //do stuff with l } 

I changed the request declaration so that it is inline and it works fine:

case # 2

  foreach (some_object l in (from candidate in next where (current.toTime + TimeSpan.FromMinutes(5) <= candidate.fromTime) orderby candidate.fromTime select candidate)) { //do stuff with l } 

Does anyone know why it does not work in case number 1? As I understand it, the request was not evaluated when you announced it, so I do not see how the difference is.

+6
source share
1 answer

Changes to current will be written, but the request already knows the value of next . Adding additional elements to an existing list will cause them to appear in the request, but changing the value of a variable to link to another list will not have any effect. Basically, if you mentally expand the query from the query expression into the "normal" form, any variable present in the lambda expression will be written as a variable, but any variable represented directly as an argument will be evaluated immediately. This will only result in displaying the reference value of the variable and not the elements present in the list, but this still means changing the value of the variable itself, which will not be visible. Your first request expands to:

 var valid_next_links = next .Where(candidate => (current.toTime + TimeSpan.FromMinutes(5) <= candidate.fromTime)) .OrderBy(candidate => candidate.fromTime); 
+7
source

Source: https://habr.com/ru/post/918471/


All Articles