Difference Between IEnumerable and IQueryable in C#

In this article , we will learn differences are between IEnumerable vs IQueryable in LinQ.

  • IEnumerable and IQueryable are used for data manipulation in LINQ from the database and collections. and both are forward collection.

IEnumerable :

1.IEnumerable exists in System.Collections Namespace.

2.IEnumerable is suitable for LINQ to Object and LINQ to XML queries.

3.IEnumerable doesn’t support lazy loading.

4.Extension methods support by IEnumerable takes functional objects.

5.Custom queries are not supported.

6.While querying data from the database, IEnumerable executes select query on the server-side, loads data in-memory on the client-side and then filters the data.

7.IEnumerable is best suitable for querying data from in-memory collections like List, Array etc.

Example :

using System;
using System.Collections.Generic;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentDBContext dBContext = new StudentDBContext();
            IEnumerable<Student> listStudents = dBContext.Students.Where(x => x.Gender == "Male");
            listStudents = listStudents.Take(2);
            foreach(var std in listStudents)
            {
                Console.WriteLine(std.FirstName + " " + std.LastName);
            }
            Console.ReadKey();
        } 
    }
}

IQueryable :

1.IQueryable exists in System. Linq Namespace.

2.IQueryable is suitable for LINQ to SQL queries.

3.IQueryable support lazy loading.

4.Extension methods support by IQueryable takes expression objects means expression tree.

5.Custom queries are supported with the help of CreateQuery as well as Execute methods.

6.While querying data from a database, IQueryable executes a select query on server-side with all filters.

7.IQueryable is best to query data from out-memory like remote database or web service etc.

Example :

using System;
using System.Linq;
namespace LINQDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentDBContext dBContext = new StudentDBContext();
            IQueryable<Student> listStudents = dBContext.Students
                                .AsQueryable()
                                .Where(x => x.Gender == "Male");
            listStudents = listStudents.Take(2);
            foreach(var std in listStudents)
            {
                Console.WriteLine(std.FirstName + " " + std.LastName);
            }
            Console.ReadKey();
        } 
    }
}

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories