What is the difference between IQueryable and IEnumerable?

前端 未结 12 1614
梦毁少年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:50

    Below mentioned small test might help you understand one aspect of difference between IQueryable<T> and IEnumerable<T>. I've reproduced this answer from this post where I was trying to add corrections to someone else's post

    I created following structure in DB (DDL script):

    CREATE TABLE [dbo].[Employee]([PersonId] [int] NOT NULL PRIMARY KEY,[Salary] [int] NOT NULL)
    

    Here is the record insertion script (DML script):

    INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(1, 20)
    INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(2, 30)
    INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(3, 40)
    INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(4, 50)
    INSERT INTO [EfTest].[dbo].[Employee] ([PersonId],[Salary])VALUES(5, 60)
    GO
    

    Now, my goal was to simply get top 2 records from Employee table in database. I added an ADO.NET Entity Data Model item into my console application pointing to Employee table in my database and started writing LINQ queries.

    Code for IQueryable route:

    using (var efContext = new EfTestEntities())
    {
        IQueryable<int> employees = from e in efContext.Employees  select e.Salary;
        employees = employees.Take(2);
    
        foreach (var item in employees)
        {
            Console.WriteLine(item);
        }
    }
    

    When I started to run this program, I had also started a session of SQL Query profiler on my SQL Server instance and here is the summary of execution:

    1. Total number of queries fired: 1
    2. Query text: SELECT TOP (2) [c].[Salary] AS [Salary] FROM [dbo].[Employee] AS [c]

    It is just that IQueryable is smart enough to apply the Top (2) clause on database server side itself so it brings only 2 out of 5 records over the wire. Any further in-memory filtering is not required at all on client computer side.

    Code for IEnumerable route:

    using (var efContext = new EfTestEntities())
    {
        IEnumerable<int> employees = from e in efContext.Employees  select e.Salary;
        employees = employees.Take(2);
    
        foreach (var item in employees)
        {
            Console.WriteLine(item);
        }
    }
    

    Summary of execution in this case:

    1. Total number of queries fired: 1
    2. Query text captured in SQL profiler: SELECT [Extent1].[Salary] AS [Salary] FROM [dbo].[Employee] AS [Extent1]

    Now the thing is IEnumerable brought all the 5 records present in Salary table and then performed an in-memory filtering on the client computer to get top 2 records. So more data (3 additional records in this case) got transferred over the wire unnecessarily.

    0 讨论(0)
  • 2020-11-22 06:51

    This is a nice video on youtube which demonstrates how these interfaces differ , worth a watch.

    Below goes a long descriptive answer for it.

    The first important point to remember is IQueryable interface inherits from IEnumerable, so whatever IEnumerable can do, IQueryable can also do.

    enter image description here

    There are many differences but let us discuss about the one big difference which makes the biggest difference. IEnumerable interface is useful when your collection is loaded using LINQ or Entity framework and you want to apply filter on the collection.

    Consider the below simple code which uses IEnumerable with entity framework. It’s using a Where filter to get records whose EmpId is 2.

    EmpEntities ent = new EmpEntities();
    IEnumerable<Employee> emp = ent.Employees; 
    IEnumerable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>();
    

    This where filter is executed on the client side where the IEnumerable code is. In other words all the data is fetched from the database and then at the client its scans and gets the record with EmpId is 2.

    enter image description here

    But now see the below code we have changed IEnumerable to IQueryable. It creates a SQL Query at the server side and only necessary data is sent to the client side.

    EmpEntities ent = new EmpEntities();
    IQueryable<Employee> emp = ent.Employees;
    IQueryable<Employee> temp =  emp.Where(x => x.Empid == 2).ToList<Employee>();
    

    enter image description here

    So the difference between IQueryable and IEnumerable is about where the filter logic is executed. One executes on the client side and the other executes on the database.

    So if you working with only in-memory data collection IEnumerable is a good choice but if you want to query data collection which is connected with database `IQueryable is a better choice as it reduces network traffic and uses the power of SQL language.

    0 讨论(0)
  • 2020-11-22 06:55

    ienumerable:when we want to deal with inprocess memory, i.e without dataconnection iqueryable:when to deal with sql server, i.e with data connection ilist : operations like add object, delete object etc

    0 讨论(0)
  • 2020-11-22 06:56

    IEnumerable: IEnumerable is best suitable for working with in-memory collection (or local queries). IEnumerable doesn’t move between items, it is forward only collection.

    IQueryable: IQueryable best suits for remote data source, like a database or web service (or remote queries). IQueryable is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries).

    So when you have to simply iterate through the in-memory collection, use IEnumerable, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable

    0 讨论(0)
  • 2020-11-22 06:56

    IEnumerable is refering to a collection but IQueryable is just a query and it will be generated inside a Expression Tree.we will run this query to get data from database.

    0 讨论(0)
  • 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<T> 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.

    0 讨论(0)
提交回复
热议问题