Wednesday, January 21, 2015

LINQ Let Keyword Using C#

LINQ Let Keyword Using C#

While exploring LINQ keywords, I encountered the Let keyword and thought to write something for .Net geeks. 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.

images


Example for the LINQ Let Clause Using C# in ASP.Net

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5:  
  6: namespace LINQ_LetKeyword
  7: {
  8:  
  9:     class Employee
 10:     {
 11:         public string Name { get; set; }
 12:         public string EmpID { get; set; }
 13:         public int Salary { get; set; }
 14:  
 15:     }
 16:     class Program
 17:     {
 18:         static void Main(string[] args)
 19:         {
 20:             //Object Initialization for Employee class
 21:             List<Employee> objEmployee = new List<Employee>{
 22:                     new Employee{ Name="Sachin",EmpID="I001",Salary=800},
 23:                     new Employee{ Name="Vijay",EmpID="I002",Salary=400},
 24:                     new Employee{ Name="Ashish",EmpID="I003",Salary=250},
 25:                     new Employee{ Name="Syed",EmpID="I004",Salary=300},
 26:                     new Employee{ Name="Ravish",EmpID="I005",Salary=700},
 27:                 };          
 28:  
 29:             var objresult = from emp in objEmployee
 30:                             let totalSalary = objEmployee.Sum(sal => sal.Salary)
 31:                             let avgSalary = totalSalary / 5
 32:                             where avgSalary > emp.Salary
 33:                             select emp;
 34:             foreach (var emp in objresult)
 35:             {
 36:                 Console.WriteLine("Student: {0} {1}", emp.Name, emp.EmpID);
 37:  
 38:             }
 39:             Console.ReadLine();
 40:         }
 41:     }
 42: }
 43: 
 44: LINQ Query 
 45:  
 46: var objresult = from emp in objEmployee
 47:                             let totalSalary = objEmployee.Sum(sal =>  sal.Salary)
 48:                             let avgSalary = totalSalary / 5
 49:                             where avgSalary > emp.Salary
 50:                             select emp;

 


//output :
LinqLet.jpg
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.


Please download the relevant code file from the link given below:


LINQ LET KEYWORD USING C#


To learn more about MVC please go to the following link.

MVC Articles

Thanks.
Keep coding and Stay Happy Smile

0 comments :

Post a Comment