Online Tutorials & Training Materials | STechies.com
Register Login

Difference between IEnumerable and IQueryable with Comparison Chart

|| 0

Difference between IEnumerable and IQueryable with Comparison Chart
Stechies

The questions related to iqueryable vs ienumerable, definition of iqueryable, definition of ienumerable, features and examples of iqueryable and ienumerable are quite commonplace in interviews. Do know that IEnumerable and IQueryable serve to be helpful for data manipulation in LINQ. The data manipulation in this context refers to databases and collections. The main difference between the two terms is that IEnumerable gets inherited by Iqueryable. Therefore, IQueryable possesses all features of IEnumerable along with its own. Significantly important when it comes to data manipulation and query data, both iqueryable and ienumerable boost LINQ Query performance in more ways than one.

Here, we aim to throw light on the difference between ienumerable and iqueryable, their features and advantages. Though both these terms appear alike and are quite similar for coding purposes, they are different in many ways. Along with helping you understand the usability scenarios for which they are recommended, this article will also explain the difference between ienumerable and iqueryable in the easiest of ways. So, are you ready to know more about ienumerable vs iqueryable? Read on.

IEnumerable vs IQueryable

Given below is an Ienumerable vs Iqueryable comparison chart for guiding your understanding of these two methods.

  Basis of Differentiation

IEnumerable

IQueryable

Namespace

The namespace in IEnumerable is System.Collections 

The namespace in IQueryable is System.Linq 

Derivation

There is no base interface

Derives the base interface from IEnumerable

Deferred Execution

Supports deferred execution

Deferred execution is not possible

Lazy Loading

Lazy loading is not supported by IEnumerable

Lazy loading is supported by IQuerytable

Functionality

In the course of querying data from databases, it is possible to observe that IEnumerable executes by selecting query on the server side, loading data in-memory on the client side and then filtering the data. As Ienumerable performs a lot more work than IQuerytable, it is much slower.

In the process of querying data from databases, IQueryable can be seen executing select query on the server side with the help of its filters. In comparison to Ienumerable it does less work and therefore showcases faster performance.

Suitable for

LINQ to XML queries and LINQ to Object.

LINQ to SQL query.

Custom Queries

Custom queries are not supported.

Custom queries are supported with the help of CreateQuery as well as Executemethods.

Extension method
parameters

The extension methods compatible with IEnumerable are supportive of functional objects.

The extension methods that are compatible with IQuerytable are known to take expression objects of the likes of expression tree.

When used

1. Working with read-only collections.
 

2. When the developer needs to read objects in the forward direction only and is not too concerned with respect to thread safety.
 

3. When the collection’s objects have to be iterated for using foreach.
 

4. While querying data from Lists, Arrays and other in-memory collections.

  1. While querying data from the out-memory collections of the likes of remote database, service, etc.
  2. Useful for working with queryable datasources.
  3. When developers find it important to apply filters on data right at the datasource.
  4. When there is a need for applying paging composition. When the work revolves around external data sources.
  5. There is a requirement to load data in a deferred way.
  6. There is a need to utilize foreach for iterating a collection.

Best use cases

For the purpose of in-memory traversal

For paging purposes

What is IEnumerable?

Ienumerable is most suited for iterating through collections. IEnumerable is basically an interface that defines the singular method GetEnumerator. This method returns an IEnumerator interface of the desired type. The IEnumerator interface allows ‘read only’ access to collections and allows iteration among the class with the help of a foreach loop.

Thereafter, the collection that implements the IEnumerable method can be utilized for the coding for-each statements. In c#, IEnumerable forms the abstract aggregate with IEnumerator being the abstract Iterator. Ienumerable is implemented by collections such as Lists. In simple words, Ienumerator relates to an iteration over non-generic collections. It forms the base interface for enumerators. Do note that enumerators can only be used for the purpose of modifying data in any collection, they cannot be used for the purpose of reading the data in a collection. In other words, IEnumerable serves as the abstract aggregate while IEnumerator happens to be the abstract Iterator.

Example:

class MyArrayList : IEnumerable

{
    object[] stech_Item = null;
    int Index = 0;

    public MyArrayList()
    {
        // For the sake of simplicity lets keep them as arrays
        // ideally it should be link list
        stech_Item = new object[100];
    }

    public void Add(object item)
    {
        // Let us only worry about adding the item
        stech_Item[Index] = item;
        Index++;
    }

    // IEnumerable Member
    public IEnumerator GetEnumerator()
    {
        foreach (object o in stech_Item)
        {
            // Lets check for end of list (its bad code since we used arrays)
            if(o == null)
            {
                break;
            }

            // Return the current element and then on next function call
            // resume from next element rather than starting all over again;
            yield return o;
        }
    }
}

Features of IEnumerable

  • IEnumerable exists in the form of System.Collections Namespace.
  • IEnumerable is capable of moving forward over a collection only. It cannot move between the items or backward.
  • IEnumerable is very useful for querying data from Lists, Arrays and other memory collections.
  • While querying data from databases, IEnumerable is helpful in executing select query on the server side; it loads data in-memory on the client side; and then filters the data.
  • IEnumerable helps LINQ handle XML queries.
  • IEnumerable supports the feature of deferred execution.
  • IEnumerable fails to support custom query or lazy loading; thus, it cannot be used effectively for paging like scenarios.
  • Extension methods are supported by IEnumerable for taking functional objects.

What is IQueryable?

IQueryable and IEnumerable are both interfaces that permit the manipulation as well as the query collection of data. As Iqueryable is inherited by Ienumerable, IQueryable adds its features to IEnumerable interfaces to help manipulate and query the collections of data. As IEnumerable is inherited by IQueryable, it effectively means that IQueryable bestows its features to the IEnumerable interface. Whenever developers have to deal with huge data containing many records, IQueryable showcases high performance by filtering data before forwarding the filtered data to clients.

Example:

using System;
using System.Collections.Generic;
using System.Linq;

class stech_main
{
    static void Main()
    {
        // List and array can be converted to IQueryable.
        List<int> list = new List<int>();
        list.Add(0);
        list.Add(1);

        int[] array = new int[2];
        array[0] = 0;
        array[1] = 1;

        // We can use IQueryable to treat collections with one type.
        Stechies(list.AsQueryable());
        Stechies(array.AsQueryable());
    }

    static void Stechies(IQueryable<int> items)
    {
        Console.WriteLine($"Sum: {items.Sum()}");
        Console.WriteLine($"Average: {items.Average()}");
    }
}

Features of IQuerytable

  • IQueryable exists in the System.Linq Namespace.
  • IQueryable moves in the forward direction in a collection only, it is incapable of moving backwards or between the items.
  • IQueryable is most useful for querying data from the out-memory collections such as remote database, service, etc.
  • In the course of querying data from databases, it is found that IQueryable is capable of executing the select query on the server side equipped with all filters.
  • IQueryable is quite suitable for LINQ when it comes to handling SQL queries.
  • IQueryable is supportive of deferred execution.
  • IQueryable supports the handling of custom query with the help of methods like CreateQuery and Execute.
  • IQueryable supports lazy loading and can be utilized for paging like scenarios.
  • Extension methods are supported by Iqueryable.

Key differences between iqueryable and ienumerable in points

The main difference existing between “IEnumerable” and “IQueryable” may be related to the location wherein the filter logic is executed. While the former is executed on the client side in memory locations, the latter is executable on databases.

  • IEnumerable can be found in the System.Collections namespace while IQueryable dominates the System.Linq Namespace.
  • IEnumerable is best utilized for querying data from the in-memory collections of the likes of Lists, Arrays and so forth. On the other hand, IQueryable is used for querying data from remote databases, services and other out-memory collections.
  • In the process of querying data from databases, IEnumerable runs the "select query" that’s present on the server-side; it loads the data in-memory fitfully on the client-side; and then proceeds to filter the data. Conversely, IQueryable executes the "select query" with all filters on the server-side.
  • IEnumerable is useful for handling the LINQ to Object as well as LINQ to XML queries. IQueryable is helpful for handling LINQ to SQL queries.
  • IEnumerable is slower in terms of its processing speed because in the course of selecting data from databases it is known to execute the select query on the server side, load the data in-memory effectively on the client side and then go about the process of filtering data. This is not applicable to IQuerytable.
  • IEnumerable is preferable mainly for small data manipulations while IQueryable is useful for performing big-sized data manipulation tasks.
  • IEnumerable<T> showcases a forward-only cursor belonging to T. .NET 3.5 added methods. These extension methods are included in the LINQ standard operators for queries like Where and First. They are compatible with those operators that need anonymous functions or functions taking Func<T>. On the other hand, IQueryable<T> implements the similar LINQ standard operator for running a query. However, it accepts the Expression<Func<T>> for anonymous functions and predicates. The Expression<T> serves to be a compiled expression tree. It functions as a broken-up version pertaining to the method that is capable of being parsed by the query table's provider and can be used accordingly.
  • If you are creating an Iqueryable it is possible for the same to be converted to sql and executed on database servers. In case of creating an IEnumerable, all rows are pulled into the memory location in the form of objects before the query is run. In these methods, in case ToArray () or ToList () is not called then the query will be run every time it is used.
  • The extension methods related to IQueryable are known to take expression objects rather than Func objects. This effectively means that the delegate received by IQueryable is in the form of an expression tree rather than that of a method that has to be invoked.
  • IEnumerable enumerates all its elements at all times even as IEqueryable is known to enumerate the elements, or perform on the things that are based on a specific query. The query happens to be an Expression or a data representation of the .Net code) that has to be explored, interpreted, compiled, etc. by the IQueryProvider for generating good results.

Conclusion

In this article dedicated to iqueryable and ienumerable, we have tried explaining the difference between IEnumerable and Iqueryable in the form of a comparison chart as well as through points. A closer look at the features and difference of ienumerable and iqueryable is likely to enhance your LINQ query performance. We would like to receive your valuable feedback on our attempt at explaining the various aspects of ienumerable and iquerytable methods. We look forward to hearing from you for your views on difference between ienumerable and iqueryable in c# with example – do send us your feedback, questions and/ or comments in the section below.