65.9K
CodeProject is changing. Read more.
Home

Into and Let in LINQ (Let vs. Into)

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.41/5 (8 votes)

Jul 26, 2011

CPOL

1 min read

viewsIcon

106789

In this post, I am going to show two keywords in C# 3.0 which are very helpful when playing with a set of object collections using LINQ.

In this post, I am going to show two keywords in C# 3.0 which are very helpful when playing with a set of object collections using LINQ.

Into

The 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 the above query, after applying into on grouping, it creates a IGrouping type gEmp variable, which is used to apply the next filter.

Note: Into is used when you want to perform an operation on grouped data.

Let

The Let keyword allows storing the results of a query which can be used in a subsequent query; i.e., it creates a new variable and initializes it with the result of the 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 };

The above query is used to find out employee(s) having salary more than avgSalary. The Let keyword allows to create a new variable avgsal that is used in further operations.

Let vs. Into

Most people find it difficult to decide which one to use when designing a LINQ query.

  • Into – Hides the previous variable when used in a query, as you see in the above example. Which means it hides the previous range variable and creates a temporary range variable which you can use in further operations.
  • Let – Doesn’t hide the previous variable and creates a new variable. Which means you create a new variable and you can also use the previous variable, so you can use both in further operations.