Into and let in LINQ ( Let vs Into)

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.

Pranay Rana

Pranay is MVB on DZone and working as a Senior Software engineer. Doing Web development using Asp.Net ,C#, MS sql server, JQuery/Javascript that he had experience of 4.3 years now. For himdef. of programming is : Programming is something that you do once and that get used by multiple for many years You can visit him on his blog - http://pranayamr.blogspot.com/ Follow on twitter : @pranayamr

One Comment to “Into and let in LINQ ( Let vs Into)”

  1. Between me and my husband we’ve owned more MP3 players over the years than I can count, including Sansas, iRivers, iPods (classic & touch), the Ibiza Rhapsody, etc. But, the last few years I’ve settled down to one line of players. Why? Because I was happy to discover how well-designed and fun to use the underappreciated (and widely mocked) Zunes are.

Comments are closed.