Introduction

Hi folks, recently we have covered IEnumerable vs IEnumerator.

Today let's try to understand why we have Iqueryable in C# when IEnumerable can get the work done.

Say we have DB mapped into our project, If you want to learn how to do that, then you can visit the first-approach step-by-step guide.

First, let's understand what IQueryable is,

There is a key difference between IQueryable & IEnumerable

IEnumerable fetches all the data from the SQL server then it applies filters over fetched data. Let's break down its flow from the client to the server.

The result of this is that it consumes more time as it transfers all the data without filtering through a network.

Where IQueryable fetches filtered records from SQLServer rather than fetching all the records altogether. Let's break-down its flow from the client to the server.

It consumes less time, as it transfers only filtered records through a network.

Let's see this in action.

Let's check what we have in the database

8 records, we will filter these records based on salary. Fetch records with a salary greater than 45000.

To understand the time consumed by both IEnumerable & IQueryable let's print the time taken by both.

IEnumerable & IQueryable

1st IEnumerable

using (var db = new EmployeeDBEntities())
{
    DateTime now = DateTime.Now;

    IEnumerable<Employee> employees = from emp in db.Employees
                                      where emp.Salary > 45000
                                      orderby emp.Salary
                                      select emp;

    Console.WriteLine("Time taken by IEnumerable: " + (DateTime.Now - now).Milliseconds + " Milliseconds");
    Console.WriteLine("Employees with salaries > 45000");

    foreach (var item in employees)
    {
        Console.WriteLine("Name: " + item.FirstName + ", Salary: " + item.Salary);
    }
}

Output

The time taken by IEnumerable is 634 milliseconds.

IEnumerable 634 milliseconds

Now let's filter data with IQueryable.

using (var db = new EmployeeDBEntities())
{
    DateTime now = DateTime.Now;

    IQueryable<Employee> employees = from emp in db.Employees
                                     where emp.Salary > 45000
                                     orderby emp.Salary
                                     select emp;

    Console.WriteLine("Time taken by IQueryable: " + (DateTime.Now - now).Milliseconds + " Milliseconds");
    Console.WriteLine("Employees with salaries > 45000");

    foreach (var item in employees)
    {
        Console.WriteLine("Name: " + item.FirstName + ", Salary: " + item.Salary);
    }
}

Output

The time taken by IQueryable is 325 milliseconds, almost half of IEnumerable.

Output

Note. The difference between this time depends on a lot of factors.

Conclusion

In this article, we learned,

Thanks a lot. I hope this article was helpful to all of you.

If you have any queries, you can ping me @