Monday, 28 March 2016

Let Keyword In LINQ C#

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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{

    class Employee
    {
        public string Name { getset; }
        public string EmpID { getset; }
        public int Salary { getset; }

    }
    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="Ankit",EmpID="I002",Salary=400},
                    new Employee{ Name="Vishal",EmpID="I003",Salary=250},
                    new Employee{ Name="Amit",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 result = from emp in objEmployee
                            let totalSalary = objEmployee.Sum(sal =>  sal.Salary)
                            let avgSalary = totalSalary / 5
                            where avgSalary > emp.Salary
                            select emp;


//output :

Student : Ankit 1002
Student : Vishal 1003
Student : Amit 1004


  • 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.

No comments:

Post a Comment