IEnumerable vs. IList

Var vs. IEnumerable in LINQ

The “var” is a keyword that implicitly types a variable and it is strongly typed also.

The “var” keyword derives type from the right hand side and its scope is in the method.

The “var” is an implicitly typed local variable. We just let the compiler determine the type i.e.
            var x = 1; //Implicitly typed.
            int y = 1; //Explicitly typed.

For example,

    var customer = ent.Customers.Where(x => x.CustId>0).ToList();
    IEnumerable<Customers> customer = ent.Customers..Where(x => x.CustId>0).ToList();

In the above example, the “var” keyword is only syntax for a programmer.  It doesn't change the semantics at all. If we declared as “var” the type of customer is still IEnumerable<Customers> and both the above query will generate the same output.

Actually, I am always using “var” keyword when I need return something from a collection rather than IEnumerable or IQueryable, because the “var” keyword can make our code faster, in some the cases so much faster.

The IEnumerable represents a forward only cursor of T.

The IEnumerable is fit for querying data from in memory collections like Array, List, and collations etc.
While us querying data from the database. The IEnumerable executes SELECT Query on the server side, load list of the data in memory on the client side and after that apply filters on the data.

The IEnumerable is best suitable for in-memory collection. It doesn’t move between items. It is forward only collection.

The IEnumerable is more useful for LINQ to XML and LINQ to object queries.


I hope it is very helpful to you! Thank you!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^