Say I have simple LINQ extenstion:
var filtered = data.Where(i => i.Count > 0);
I know that this will not evaluated unless I start to use filtered i.e.
foreach(DataItem i in filtered) ...
However I need to create cloned version of data
and release data as soon as possible. data
can be changed in other thread so I want to get immediate snapshot of it.
How can I force filtered
to be evaluated immediately?
LINQ queries are always executed when the query variable is iterated over, not when the query variable is created. This is called deferred execution. You can also force a query to execute immediately, which is useful for caching query results. This is described later in this topic.
Materializing LINQ Queries Once When writing LINQ queries using IEnumerable or IQueryable interfaces, developers can materialize (call ToList , ToArray or similar methods) or not to materialize queries immediately (Lazy loading). The lack of materialization allows developers to work with collections lazily.
Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.
var filtered = data.Where(i => i.Count > 0).ToArray();
// or
var filtered = data.Where(i => i.Count > 0).ToList();
To get a list populated with the result of the enumeration, call ToList()
, i.e.,
var filtered = data.Where(i => i.Count > 0).ToList();
To side-effect the sequence:
var filtered = data.Where(i => i.Count > 0).Run();
You may want to explore Reactive Extension for .NET 3.5/4.0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With