While exploring LINQ keywords, I encountered the Let keyword and thought to write something for .Net geeks. I've taken an idea from my previous article on http://www.c-sharpcorner.com about DefaultIfEmpty() and utilized similar code. You can look at this article here: http://www.c-sharpcorner.com/UploadFile/97fc7a/linq-method-defaultifempty/.
The Let keyword gives you the liberty to use its value for the next level. This is the beauty of this keyword, that you can utilize the value on the next statement, which helps you keep your code simpler and easier to understand.
Example for the LINQ Let Clause Using C# in ASP.Net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQ_LetKeyword
{
class Employee
{
public string Name { get; set; }
public string EmpID { get; set; }
public int Salary { get; set; }
}
class Program
{
static void Main(string[] args)
{
//Object Initialization for Employee class
List<Employee> objEmployee = new List<Employee>{
new Employee{ Name="Sachin",EmpID="I001",Salary=800},
new Employee{ Name="Vijay",EmpID="I002",Salary=400},
new Employee{ Name="Ashish",EmpID="I003",Salary=250},
new Employee{ Name="Syed",EmpID="I004",Salary=300},
new Employee{ Name="Ravish",EmpID="I005",Salary=700},
};
var objresult = from emp in objEmployee
let totalSalary = objEmployee.Sum(sal => sal.Salary)
let avgSalary = totalSalary / 5
where avgSalary > emp.Salary
select emp;
foreach (var emp in objresult)
{
Console.WriteLine("Student: {0} {1}", emp.Name, emp.EmpID);
}
Console.ReadLine();
}
}
}
LINQ Query
var objresult = from emp in objEmployee
let totalSalary = objEmployee.Sum(sal => sal.Salary)
let avgSalary = totalSalary / 5
where avgSalary > emp.Salary
select emp;
//output :
I've tried to use the very simplest way to describe the "Let" keyword. Yet I look forward to your advise on this, whether I could present it in a more convenient way and if so then how.
Cheers.