Ehsan Ghanbari

Experience, DotNet, Solutions

Note about the Deferred Execution in LINQ component

Maybe you know about the deferred execution unconsciously. This sexy phrase refers to the point of LINQ queries when it executed. Although executing the LINQ query should be considered and after doing join, group, let and every LINQ instructions, finally, it should be executed; because it will be executed in every call if you don't execute it! Take a look at the following example:

  public IEnumerable<Blog> GetAllPosts()

        {

            var executedQuery =_siteContext.Blogs.

                Where(p => p.IsDeleted == false && p.IsPublished)

                .OrderByDescending(c => c.CreationDate)

                .Include(c => c.Tags)

                .ToList();

           var count = executedQuery .Count();

           var average= executedQuery.Contains("d");

           return executedQuery ;

        }

As you can see the executed Query has been executed by .ToList() and the Count() and Contains("d") will be queried in memory and If you don't call .ToList() it will be executed in each of the mentioned LINQ methods.



About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns. I spend a lot of time on software architecture. Since 2008, I've been as a developer for different companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the past years, Read More

Post Tags
Pending Blog Posts
using Elmah in asp.net MVC4
Using FluentSecurity in MVC
Strategic design
Factory Pattern
time out pattern in ajax
Redis as a cache server
How to use PagedList In asp.net MVC
Multiple submit buttons in asp.net MVC
Domain driven design VS model driven architecture
What's the DDD-lite?