Saturday, May 28, 2011

Into and let in LINQ ( Let vs Into)

Shout it kick it on DotNetKicks.com
In this post I am going to show two keyword of the C# 3.0 is very helpful when playing with the set of object collection using LINQ feature.

Into
Into keyword allows creating a temporary variable to store the results of a group, join or select clause into a new variable.
var em = from e in emp
                      group e by new{ e.DeptId}
                          into gEmp 
                          where gEmp.Count() > 1
                       select new { gEmp.Key.DeptId, salary = gEmp.Sum(t => t.Salary) };
In above query after applying into on groping it creates IGroping type gEmp variable, which used to apply next filter.
Note: Into is use full when you want to perform the operation on the groped data.

Let
Let keyword allows storing the result of the query which can be used in subsequent query i.e it creates new variable and initializes it with the result of expression you supply.
var em = from e in emp
                     group e by new { e.Salary, e.Id }
                         into gEmp
                         let avgsal = (gEmp.Sum(t => t.Salary) / gEmp.Count())
                         where gEmp.Key.Salary == avgsal
                         select new { gEmp.Key.Salary, gEmp.Key.Id };
Above query is used to find out the employee(s) having the salary more than avgSalary. Let keyword allows to create new variable avgsal that used in the further operation.

Let vs Into
Most of the people find difficult which one is to use either Let or Into when designing Linq query.
Into – Hides the previous variable when used in query as you see in above example. Which means its hides previous range variable and create temporary range variable which you can use in further operation.
Let – doesn’t hide the previous variable and create new variable. Which means you created new variable and you can also use the previous variable so you can use both in the further operation.