score:0
a linq query is executed when it has a underlying collection but it is not a collection. you can materialze a query for example by using tolist()
or toarray
.
every deferred executed enumerable
extension tries first to cast the ienumerable<t>
to an ilist<t>
(f.e. if it needs an indexer) or to a icollection<t>
(f.e. if it needs a count
). if it can, it will use the "native" method which does not need to execute the query, otherwise it will enumerate the sequence.
search for the tem deferred on msdn to see whether a method is executexd deferred or immediately. if you inspect the source code(f.e. via ilspy
), you can detect deferred executed methods by looking for the yield keyword
.
union
and except
are implemented using deferred execution. so you need a tolist
/toarray
if you want to persist that result.
here's an example, the implementation of enumerable.count
:
icollection<tsource> collection = source as icollection<tsource>;
if (collection != null)
{
return collection.count;
}
icollection collection2 = source as icollection;
if (collection2 != null)
{
return collection2.count;
}
int num = 0;
using (ienumerator<tsource> enumerator = source.getenumerator())
{
while (enumerator.movenext())
{
num++;
}
}
return num;
score:1
answer on your question depends on two options:
- type of operation: lazy (or deferred) and greedy. lazy operations wouldn't be executed immediatly, and defered until code will start materializing data from your linq source. greedy operations always execute immediatly.
- example of lazy operations:
.union
,.except
,.where
, .select
and most of other linq operations - greedy are:
.tolist
,.count
.toarray
and all operations that materialize data
- example of lazy operations:
- source of data for your linq operations. while you're working with linq to memory all operations (both lazy and greedy) will be executed immediately. usualy linq to external sources of data will execute lazy operations only during materialization.
using this two rules you could anticipate how linq will behave:
.count
and.tolist
will execute immediatly and materialize data- after
.tolist
, you'll get collection at memory, and all following operations will be executed immediatly (.count
will execute one again) - how will
.union
and.except
behave as lazy or greedy depends on type of your data source. for memory they will be greedy, for sql lazy.
example for linqpad. i have one enumerable
and lazy or deferred .where
and .select
operations on it before and after materializing using greedy .count
or .tolist
:
void main()
{
"get enumerable".dump();
var samplesenumerable = getsamples();
"get count on enumerable #1".dump();
samplesenumerable.count().dump();
"get enumerable to list #1".dump();
var list = samplesenumerable.tolist();
"get count on list #1".dump();
list.count().dump();
"get count on list again #2".dump();
list.count().dump();
"get where/select enumerable #1".dump();
samplesenumerable
.where(sample => { sample.dump(); return sample.contains("5"); })
.select(sample => { sample.dump(); return sample; })
.dump();
"get where/select list #1".dump();
list
.where(sample => { sample.dump(); return sample.contains("5"); })
.select(sample => { sample.dump(); return sample; })
.dump();
}
string[] samples = new [] { "data1", "data2", "data3", "data4", "data5" };
ienumerable<string> getsamples()
{
foreach(var sample in samples)
{
sample.dump();
yield return sample;
}
}
sample output. key points
on not materialized data, every
.count
and.list
are retrieving data again and againget count on enumerable #1
get where/select enumerable #1
after materializing data, enumerable will be not retreived any more
get enumerable to list #1
get count on list #1
get count on list again #2
get where/select list #1
output:
get enumerable
get count on enumerable #1
data1
data2
data3
data4
data5
5
get enumerable to list #1
data1
data2
data3
data4
data5
get count on list #1
5
get count on list again #2
5
get where/select enumerable #1
data1
data1
data2
data2
data3
data3
data4
data4
data5
data5
data5
data5
get where/select list #1
data1
data2
data3
data4
data5
data5
data5
score:2
union and except are deferredly executed. read remarks section in documentation for more info.
http://msdn.microsoft.com/en-us/library/bb341731
http://msdn.microsoft.com/en-us/library/bb300779
also, in such situation when you are note sure what's happening under the hood, you can use reflector or any other .net decompiler. it's really helpful.
Source: stackoverflow.com
Related Query
- IList vs IEnumerable : when they "executes" the LINQ query?
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- Is there any way to create a LINQ query as a variable without having the data source (yet)?
- What is the LINQ query to get a Cartesian Product even when one set is EMPTY?
- How can I write the following code more elegantly using LINQ query syntax?
- When to expect IEnumerable and when to expect IQueryable from a Linq query
- How to use expressions to build a LINQ query dynamically when using an interface to get the column name?
- Determine the source DataContext for a Linq to Sql query
- How to solve LINQ to Entity query duplication when the queries only differ by a property?
- LINQ query returns old results when source list is re-initialized
- why the sql query is different on that linq query when run on c# and on vb.net?
- is it possible to use Take in LINQ when the query returns an anonymous type?
- Are LINQ .OrderBy().ThenBy() Operators redundant when the original Query uses the ORDER BY clause?
- Getting the first result from a LINQ query - why does ElementAt<T>(0) fails when First<T>() succeeds?
- How to get the value of class properties with Linq query and IEnumerable
- Why doesn't Visual Studio 2010 allow the use of "is null" in a linq query when VS2017 does?
- When does this LINQ query go to the database?
- Linq to Sql NotSupportedException "The explicit construction of the entity in a query is invalid" when selecting new Type of other Database Table
- Linq sub query when using a repository pattern with EF code first
- How to return null when the Linq query returns empty value?
- Improving a LINQ query so that it executes completely in the database
- How to get the index of int array when using linq query
- Getting 'Data source is an invalid type' when binding Linq query to Gridview
- C#: Using LINQ on a derived iterator class when both the derived class and its base implement IEnumerable
- How do I determine the source of unpredictable LINQ query results?
- Linq query results in the same references when initializing a variable
- How can I use a predicate in a crm sdk 2011 linq query when the query contains a join?
- Can I use a LINQ IEnumerable result as the data source for a Gtk.TreeView?
- When is the LINQ query actually get executed?
- Reduce the line of code for this LINQ query
More Query from same tag
- LINQ which return Dictionary<string, List<Item>> from collection C#
- How to extract result of Linq Expression?
- Entity Framework 6 Linq results for master-detail
- how to optimize FirstOrDefault Statement in linq
- converting VB.Net Linq to C# Linq
- LINQ causing my obfuscator to break
- Joining three tables and using a left outer join
- C# LINQ calculated Group By
- How to get total count of each month in return using entity framework core
- Linq Expression Chain Syntax for In Query
- Marking lambda expression with async keyword
- Return values of dictionary except for a given key
- filter based on parent attribute
- Linq query not returning anything
- Convert collection of IEnumerable using LINQ
- Read first row of excel sheet using OpenXML and LINQ
- Can these two LINQ-to-SQL queries be combined?
- VB.NET using LINQ to transpose an ObservableCollection
- Recursive call to compare object properties
- Counting navigation property occurrence
- Select values for a range of given indexes using Linq C#
- LINQ group by Hour and Type (click/open ratio)
- Rewrite Lambda expression with System.Linq.Expressions APIs
- Check if ALL items in Array exist in Dictionary
- Difference between Expression<Func<>> and Func<>
- Unable to produce a chart using linq in csharp
- Check if object exists in a VB.NET dictionary using Primary Key
- Linq IN statement to exclude from a list
- Empty result set when Joining two table with Non-match Foreign key
- Aggregate duplicate members of an object in C# using LINQ / Lambda