IEnumerable vs IQueryable in C#
Tags: csharp, dotnet, programming, beginners
Published: 2023-05-19 09:29:08

## IEnumerable 

IEnumerable is the base interface for all non-generic collections that can be enumerated. IEnumerable contains a single method, GetEnumerator, which returns an IEnumerator. IEnumerator provides the ability to iterate through the collection by exposing a Current property and MoveNext and Reset methods.

## Yield

The yield keyword performs custom iteration over a collection like list, array, etc. The yield keyword is used in two forms:

- yield return - returns an expression at each iteration.
- yield break - terminates the iteration.

Let us understand the concept with an example;

```
using System;
using System.Collections.Generic;
class Program
{
    // define an iterator method
    static IEnumerable<int> getNumber()
    {
        // create a list of integers 
        List<int> myList = new List<int> { -1, -4, 3, 5 };

        foreach (var num in myList)
        {
            // returns positive number from myList 
            if (num >= 0)
            {
                yield return num;

                // location of the code is preserved 
                // so on the next iteration getNumber() is executed from here 
                Console.WriteLine("....");
            }
        }
    }
    static void Main()
    {
        // display return values of getNumber() 
        foreach (var items in getNumber())
        {
            Console.WriteLine(items);
        }
    }
}
```
In the above example, we have created an iterator method getNumber() inside which we have used yield return.

Here, when getNumber() is called from foreach of Main(), the code inside getNumber() is executed until it reaches yield return.

When it reaches yield return, the current location of the code is preserved and the control goes back to the caller(i.e. foreach loop) and 3 is printed.

In the next iteration of foreach, the getNumber() method is called again. This time, getNumber() is executed from the preserved location of the code.


![Yield_Working](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xpvewsf3fg0z3l1ft1nc.png)


**Difference**

Amongst many known to us here is one big difference. “IQueryable” 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”. 


![Difference_1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nyueh213szd8zyd0jcpo.png)

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”.

But now see the below code we have changed “IEnumerable” to “IQueryable”.
![Difference_2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/usd03hedqbideyguu8dr.png)

In this case the filter is applied on the database using the “SQL” query. So the client sends a request and on the server side a select query is fired on the database and only necessary data is returned.

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.

## Connects

Check out my other blogs: 
[Travel/Geo Blogs](shishsingh.wordpress.com)
Subscribe to my channel: 
[Youtube Channel](youtube.com/@destinationhideout)
Instagram:
[Destination Hideout](https://www.instagram.com/destinationhideout/)

## References

- [IEnumerable_MS](https://learn.microsoft.com/en-us/dotnet/api/system.collections.ienumerable?view=net-7.0)

- [IEnumerable_CSC](https://www.c-sharpcorner.com/UploadFile/0c1bb2/ienumerable-interface-in-C-Sharp/)

- [Yield_Desc](https://www.programiz.com/csharp-programming/yield-keyword)

- [Difference](https://www.linkedin.com/pulse/ccsharp-interview-questions-answers-part-4-shivprasad-koirala)

- [Cover](https://www.bairesdev.com/technologies/csharp/)