LINQ - Deferred execution

本文介绍了LINQ中延迟执行的概念及其实现方式,并通过具体示例对比了立即执行与延迟执行的区别。当返回IEnumerable或IQueryable类型时,查询将在迭代元素时才执行;而返回如ToList()等操作时,则会立即执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*

Author: Jiangong SUN

*/

Deferred Execution is used in LINQ, and it means the query is not executed when declaring it; but when calling it.

If you return IQueryable or IEnumerable in your query, the query will not be executed immediately, it will be executed only when you iterate its elements.

But if you return operations on IQueryable or IEnumerable like .ToList(), Count() etc, it will be executed immediately.


Let's see some examples:


        public void EnumerableCustomers()
        {
            int id = 10;
            //differed execution: when query returns IEnumerable or IQueryable
            var query = from c in Context.Customers
                        where c.CustomerId > id
                        select c;
            id = 20; //this value is finally used because it's the latest value
            Console.WriteLine("Query result:");
            //return customer names whose id is larger than 20
            foreach (var customer in query)
                Console.WriteLine(customer.CustomerName);
        }

        private void EnumerableCustomers2()
        {
            int id2 = 10;
            //immediate execution: when query doesn't return IEnumerable or IQueryable
            var query2 = (from c in Context.Customers
                          where c.CustomerId > id2
                          select c).ToList();
            id2 = 20; //this value is not used in this case
            Console.WriteLine("Query2 result:");
            //return customer names whose id is large than 10
            foreach (var customer in query2)
                Console.WriteLine(customer.CustomerName);
        }

I hope this article can do help to you! Enjoy coding!


references:

http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx

early binding, late binding:

http://blogs.msdn.com/b/cburrows/archive/2008/10/27/c-dynamic.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值