Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ How to force query to materialize?

Tags:

c#

linq

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?

like image 682
Boppity Bop Avatar asked Jun 16 '10 22:06

Boppity Bop


People also ask

When LINQ query is executed?

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.

What is LINQ materialization?

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.

What is deferred execution in LINQ?

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.


3 Answers

var filtered = data.Where(i => i.Count > 0).ToArray();

// or

var filtered = data.Where(i => i.Count > 0).ToList();
like image 71
LukeH Avatar answered Oct 18 '22 07:10

LukeH


To get a list populated with the result of the enumeration, call ToList(), i.e.,

var filtered = data.Where(i => i.Count > 0).ToList(); 
like image 37
jball Avatar answered Oct 18 '22 08:10

jball


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.

like image 23
Thurein Avatar answered Oct 18 '22 08:10

Thurein