IntroductionIn this article I will show, what is use of Var and IEnumerable when retrieve data with LINQ Query.Var derives type from the right hand side. And its scope is in the method. And it is strongly typed. IEnumerable is interface which allows forward movement in the collection. ImplementationWe have seen normally Or Now question is where to use var or IEnumerable? Let us first have a look on both keywords.Var derives type from the right hand side. And its scope is in the method. And it is strongly typed. IEnumerable is interface which allows forward movement in the collection. LINQ where to use what ?If we really do not have idea that what would be the type of query then we will be using var. and if we are sure about the type of output then we would be using IEnumerable . Using IEnumerable <T>In the below example, 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. Example 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 Using VarNow 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 If you see the above query we do not know the type of result. Example 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 That's all, hopes help and thank you for reading. |