Var versus IEnumerable in LINQ


We have seen normally
1.gif

Or

2.gif

Now question is where to use var or IEnumerable? Let us first have a look at both key words

Var derives type from the right hand side. And its scope is in the method. And it is strongly typed. IEnumerable is an interface which allows forward movement in the collection.

Now in LINQ where to use what

If we really do not have an idea of what would be the type of query then we will be using var. Aand if we are sure about the type of output then we would be using IEnumerable .

Using IEnumerable <T>

In the example below, we are querying in collection of string so we know the output would be collection of string, so we are using here IEnumerable with string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;
 
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
 
            List<string> lstStrings = new List<string> {"Dhananjay Kumar",
                                                         "Mahesh Chand",
                                                         "John papa",
                                                         "Mike Gold",
                                                         "Shiv Prasad Koirala",
                                                          "Victor ",
                                                           "Pinal Dave" };
 
            IEnumerable<string> result = from r in lstStrings select r;
            foreach (var r in result)
            {
                Console.WriteLine(r);
            }
 
            Console.ReadKey(true);
        }
    }
}

Output

3.gif

Using var

Now if we don't know exactly what would be the type of result in that case we will be using var. There might be some scenario where you want to return anonymous type from the query

4.gif

If you see the above query we do not know the type of result.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq.Mapping;

namespace ConsoleApplication2
{

    class Program
    {
        static void Main(string[] args)
        {
 
         DataClasses1DataContext context = new DataClasses1DataContext();
         var result = from r in context.Persons select new { NameOfperson = r.FirstName + r.LastName};
         foreach (var r in result)
         {
          Console.WriteLine(r.NameOfperson);
          }
            Console.ReadKey(true);
        }
    }
}

Output 

5.gif

Up Next
    Ebook Download
    View all
    Learn
    View all