C #, the difference between IQueryable and IEnumerable

In a recent interview, I asked about the difference between IQueryable and IEnumerable, and I read some articles, are summarized as follows:

1. To understand that, IQueryable inherits from IEnumerable interface is the interface.

2. IQueryable expression trees there, it can be seen as one of its advantages. Therefore, when using IQueryable operations, such as data filtering, sorting and other operations, which will first be cached expression tree. When database operations actually take place, it will execute the expression tree to retrieve the data.

   That is to say, such as selecting two top 2 rows of data, it will first cache fetches the filter top 2 in the expression tree. Until the time of operation of the database, it will filter top 2 data in the database. = "IQueryable there is a delay loading mechanism, which filter the data directly from the database.

3. IEnumerable, its data to operate, and IQueryable different, it will advance all the data retrieved from the database into memory. Then, the data in the memory of the filtering operation, including filtering, sorting, etc.. => IEnumerable in the data memory filter

 

We use an example to illustrate the Repository by lift

public class EmployeeRepository : IEmployeeRepository
{
    private readonly CompanyContext  _context;

    public EmployeeRepository(CompanyContext  context)
    {
         _context = context;
    } 


    public IEnumerable<Employee> GetIEnumerableEmployees()
    {
        return _context.Employees;
    }

   public IQueryable<Employee> GetIQueryableEmployees()
    {
        return _context.Employees;
    }
 
}

 

Guess you like

Origin www.cnblogs.com/wphl-27/p/10979413.html