IQueryable 和IEnumberable的区别

一、IEnumerable接口
公开枚举器,该枚举器支持在指定类型的集合上进行简单的迭代。即:实现了此接口的object,就可以使用foreach遍历该object;

二、IQueryable 接口

提供对未指定数据类型的特定数据源的查询并进行计算的功能。public interface IQueryable : IEnumerable

它继承 IEnumerable 接口,.net版本加入Linq和IQueryable后,使得IEnumerable不再那么单调,变得更加强大和丰富。

三、为了区分二者的区别,代码参考:

#region 数据列表

        /// <summary>

        /// 数据列表

        /// </summary>

        /// <returns></returns>

        public ActionResult List()

        {

            //IQueryable

            IQueryable<StudentModel> userlistIQue = (from u in db.Student

                                   orderby u.id

                           select u).Skip<StudentModel>(1).Take<StudentModel>(2);

 

            //IEnumerable

            IEnumerable<StudentModel> userlistIEnu = (from u in myteref.m_user

                                                orderby u.id

                                                select u).AsEnumerable<StudentModel>().Skip<StudentModel>(1).Take<StudentModel>(2);

            int i = 0;

            foreach (var c in studentlistIQue)

            {

                i++;

            }

            Console.WriteLine(i);

 

            foreach (var c in studentlistIEnu)

            {

                i++;

            }

            Console.WriteLine(i);

            return View();

                             

        }

        #endregion

 

四、总结:

IEnumerable查询必须在本地执行.并且执行查询前我们必须把所有的数据加载到本地.而且更多的时候.加载的数据有大量的数据是我们不需要的无效数据.但是我们却不得不传输更多的数据。
使用IEnumerable,所有对于IEnumerable的过滤,排序等操作,都是在内存中发生的。也就是说数据从数据库中获取放到到了内存中,然后在内存中进行过滤和排序操作。

IQueryable却总能只提供你所需要的数 据.大大减少了数据的传输
IQueryable的优势是它有表达式树,所有对于IQueryable的过滤,排序等操作,都会先缓存到表达式树中,只有当真正遍历发生的时候,才会将表达式树由IQueryProvider执行获取数据操作。

posted @ 2014-08-17 19:17  "程序猿"~在路上  阅读(1660)  评论(0编辑  收藏  举报