What's the difference between IQueryable and I

2019-01-04 16:23发布

I'm confused as to the difference. Being fairly new to .Net, I know I can query IEnumerables using the Linq extensions. So what is this IQueryable and how does it differ?


See also What is the difference between IQueryable[T] and IEnumerable[T]? that overlaps with this question.

7条回答
2楼-- · 2019-01-04 16:56

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 extend your query:

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

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

查看更多
登录 后发表回答