07
DecUnderstanding Var and IEnumerable with LINQ
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:
IEnumerable Type with LINQ
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:
Note
In the LINQ query, use the Var type when you want to make a "custom" type on the fly.
In LINQ query, use IEnumerable when you already know the type of query result.
In LINQ query, Var is also good for remote collection since it behaves like IQuerable.
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...!