var vs ienumerable when retrieving linq query

Observe the two linq queries given below. In query1, we have used the var type to store the linq query. In query2, we have used the type IEnumerable to store the linq query. Both the queries perform the same task. However, we need to use the var type or the IEnumerable type appopriately. In this article we will see when to use var and IEnumerable when we retrieve data with LINQ Query.

Query1:
var queryByCity =
	from cust in customers
	group cust by cust.City;
Query2:
List cities = new List(); 	
	cities.Add("New Delhi");                  	
	cities.Add("Bangalore");                   	
	cities.Add("Hyderabad");                	
	cities.Add("Bombay");   
IEnumerable query = from c in cities 
			where c.Length > 8
			orderby c
			select c;
Using IEnumerable

We use the IEnumerable type when we know exactly the output of the query. For example, in the above query, we query the collection of strings and we know the output is of type string. So we use IEnumerable in the query.

Using Var

We use the var keyword when we want the compiler to determine the type returned when the query is executed. We use this type of query when we are not sure of the type of the result which will be returned by the query. We also use this query when we know that the data being returned is of anonymous type. Observe the below query.

string connectionString = "Data Source=LocalHost; Initial CataLog=SalesOrderManagement;Integrated Security=True";
	DataContext db = new DataContext(connectionString);
	Table Customers = db.GetTable();
	var query = from c in Customers
				select new { c.Name, c.Address };
	foreach (var row in query)
	{                
		Console.WriteLine(row.Name + row.Address);      
	}
You will see from the above query that the type of result cannot be determined. The query returns an anonymous type with two members - Customer Name and address. A class definition is not written in the program. we use the var keyword in such a situation. When the compiler sees the var keyword, it does not expect what type is the result and prepares to check it by itself.