Understanding Var and IEnumerable with LINQ

Understanding Var and IEnumerable with LINQ

29 Mar 2024
Intermediate
115K Views
5 min read
Learn via Video Course & by Doing 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

Q1. Can LINQ be used for IEnumerable?

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

Q2. What is an IEnumerable variable?

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.

Q3. Is IEnumerable better than List?

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

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this