Reader Level:
ARTICLE

Let Operator in LINQ

Posted by Jignesh Trivedi Articles | LINQ January 17, 2013
LINQ has one operator called “Let” that allows us to create / declare variables inside the LINQ query.
  • 0
  • 0
  • 9069
Download Files:
 

Introduction

LINQ has one operator called "Let" that allows us to create / declare variables inside the LINQ query. The benefit of using "Let" is that it makes the query very readable and using this we can create a variable and assign a calculated value in that variable. Then later part of the query can be used either in a select clause or as a where clause or Order by clause.

The "Let" operator must be used before a select statement to hold the result.

Example

In the following example, we have two tables, EmployeeMasters and DepartmentMasters. The relation between these two tables is one department has many employees so we can say there is a one-to-many relationship between these two tables.

Image 1.jpg

As we know, the "Let" Operator allows us to create a variable in the LINQ query and we can use it in a later part of the query.

In this example we store the department code in the "dep" variable that specifies the association with the employee.

Entities e = new Entities();
var empDetail = from emp in e.EmployeeMasters
                let dep = emp.DepartmentMaster == null ? "" : emp.DepartmentMaster.DepartmentCode
                select new Detail
                {
                    EmployeeId = emp.EmployeeId,
                    EmployeeCode = emp.EmployeeCode,
                    EmployeeName = emp.EmployeeName,
                    DepartmentCode = dep,
                                   };

Equivalent SQL Query

SELECT
[Extent1].[EmployeeId] AS [EmployeeId],
[Extent1].[EmployeeCode] AS [EmployeeCode],
[Extent1].[EmployeeName] AS [EmployeeName],
CASE WHEN ([Extent2].[DepartmentId] IS NULL) THEN N'' ELSE [Extent2].[DepartmentCode] END AS [C1]
FROM  [dbo].[EmployeeMasters] AS [Extent1]
LEFT OUTER JOIN [dbo].[DepartmentMasters] AS [Extent2] ON [Extent1].[DepartmentId] = [Extent2].[DepartmentId]

We can also use the "Let" operator to store a calculated field within the Query.

var emp3 = from emp in e.EmployeeMasters
            let fullName = emp.EmployeeCode + " - " + emp.EmployeeName
            select new Detail
            {
                EmployeeId = emp.EmployeeId,
                EmployeeCode = emp.EmployeeCode,
                EmployeeName = fullName,
            };

Conclusion

Using the "Let" Operator, we can create a variable in a query. This allows us to treat the result as a variable that we can then manipulate before getting the final result. We must use the "Let" before the select statement to hold the result.

COMMENT USING

Trending up