你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / C专栏
LINQ - Deferred execution
 
/*
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
  推荐精品文章

·2024年9月目录 
·2024年8月目录 
·2024年7月目录 
·2024年6月目录 
·2024年5月目录 
·2024年4月目录 
·2024年3月目录 
·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录
·2023年10月目录
·2023年9月目录 
·2023年8月目录 

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089