Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Understanding Var and IEnumerable with LINQ

Understanding Var and IEnumerable with LINQ

29 Mar 2024
Intermediate
117K Views
5 min read
Learn with an interactive course and practical hands-on labs

ASP.NET MVC with WebAPI Course

Var and IEnumerable with LINQ: An Overview

In the previous article, We saw the difference between IEnumerable and IQuerable, also IEnumerable and IList. In this article, I would like to elaborate on Var and IEnumerable with LINQ.

IEnumerable is an interface that can move forward only over a collection, it can’t move backward and between the items. Var is used to declare implicitly typed local variables means it tells the compiler to figure out the type of the variable at compilation time. A var variable must be initialized at the time of declaration. Both have their importance to query data and data manipulation.

Var Type with LINQ

We have seen normally the basic syntax of var:

Now the question is where to use var.Var derives type from the right-hand side. And its scope is in the method. And it is strongly typed.Now let's see in LINQ how to use var.If we do not have an idea what would be the type of query then we will be using var.

Example of Var Type


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace HelloWorld
{
 class Program  
    {  
        static void Main(string[] args)  
        {  
            List list = new List();  
            list.Add(new Person { Name="Pragya",Age=27 });  
            list.Add(new Person { Name="Jayanti", Age=20 });  
            list.Add(new Person { Name="Sakshi", Age=21 });  
            list.Add(new Person { Name="Pragati", Age=22 });  
            var result = from t in list  
                         orderby t.Name  
                         select new  
                         {  
                             t.Name,  
                             t.Age  
                         };  
            foreach (var item in result)  
            {  
                Console.WriteLine(item.Age);  
                Console.WriteLine(item.Name);  
            }  
        }  
  
        public class Person  
        {  
            public string Name { get; set; }  
  
            public int Age { get; set; }  
        }  
    }  
	}

Output

20
Jayanti
22
Pragati
27
Pragya
21
Sakshi

Explanation:

If you see the above code we do not know the type of result first. Var is used to declare implicitly typed local variables means it tells the compiler to figure out the type of the variable at compilation time. Hence if we don’t know exactly what would be the type of result in that case we use var.

IEnumerable Type with LINQ

We have seen normally the basic syntax of IEnumerable :

IEnumerable is an interface that allows forward movement in the collection. If we are sure about the type of output then we use IEnumerable.So it is as simple as it is. Now let's see in LINQ how to use IEnumerable.

Example of IEnumerable


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace HelloWorld
{
	public class Program
	{
		public static void Main(string[] args)
		{
			IEnumerable numbers = new int[] { 1, 2, 3, 4, 5 };

foreach (int number in numbers)

{

Console.WriteLine(number);

}
		}
	}
}

Output

1
2
3
4
5

Explanation:

IEnumerable is the most basic collection type. IEnumerable represents a sequence of elements that can be enumerated, but it does not provide any methods for modifying the sequence. So Use it when you need to iterate over a sequence of elements, but you don't need to modify the sequence.

Note

  1. In the LINQ query, use the Var type when you want to make a "custom" type on the fly.

  2. In LINQ query, use IEnumerable when you already know the type of query result.

  3. In LINQ query, Var is also good for remote collection since it behaves like IQuerable.

  4. IEnumerable is good for in-memory collection.

Summary

In this article, I tried to explain when to use Var and IEnumerable with LINQ while writing your LINQ query. I hope after reading this article you will be able to do this. I would like to have feedback from my blog readers. Please post your feedback, questions, or comments about this article. Enjoy Coding...!

FAQs

All LINQ methods are extension methods to the IEnumerable<T> interface.

we can mostly think of it as an array or a list. We can use a foreach statement to loop through it, also we can use LINQ to map or reduce it in a hundred different ways, or you can explicitly cast it to an array.

 Yes,It is best for read-only collections, while List is better for collections that can be modified
Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this