What is the difference between IQueryable and IEnumerable?

前端 未结 12 1641
梦毁少年i
梦毁少年i 2020-11-22 06:41

What is the difference between IQueryable and IEnumerable?


See also What\'s the difference between IQueryable and I

12条回答
  •  误落风尘
    2020-11-22 06:57

    In real life, if you are using a ORM like LINQ-to-SQL

    • If you create an IQueryable, then the query may be converted to sql and run on the database server
    • If you create an IEnumerable, then all rows will be pulled into memory as objects before running the query.

    In both cases if you don't call a ToList() or ToArray() then query will be executed each time it is used, so, say, you have an IQueryable and you fill 4 list boxes from it, then the query will be run against the database 4 times.

    Also if you extent your query:

    q.Where(x.name = "a").ToList()
    

    Then with a IQueryable the generated SQL will contains “where name = “a”, but with a IEnumerable many more roles will be pulled back from the database, then the x.name = “a” check will be done by .NET.

提交回复
热议问题