c# - How does the following LINQ statement work? -
how following linq statement work?
here code:
var list = new list<int>{1,2,4,5,6}; var = list.where(m => m%2 == 0); list.add(8); foreach (var in even) { console.writeline(i); } output: 2, 4, 6, 8
why not 2, 4, 6?
the output 2,4,6,8 because of deferred execution.
the query executed when query variable iterated over, not when query variable created. called deferred execution.
-- suprotim agarwal, "deferred vs immediate query execution in linq"
there execution called immediate query execution, useful caching query results. suprotim agarwal again:
to force immediate execution of query not produce singleton value, can call
tolist(), todictionary(), toarray(), count(), average()ormax()method on query or query variable. these called conversion operators allow make copy/snapshot of result , access many times want, without need re-execute query.
if want output 2,4,6, use .tolist():
var list = new list<int>{1,2,4,5,6}; var = list.where(m => m%2 == 0).tolist(); list.add(8); foreach (var in even) { console.writeline(i); }
Comments
Post a Comment