This example explains use of let keyword in linq. The ‘let’ keyword is useful in query syntax. It projects a new range variable, allows re-use of the expression and makes the query more readable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | /** * Implement let condition using LINQ C#. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; class Student { public string Name { get; set; } public string Regno { get; set; } public int Marks { get; set; } } class Program { static void Main(string[] args) { List<Student> objStudent = new List<Student>{ new Student{ Name="Tom",Regno="R001",Marks=80}, new Student{ Name="Bob",Regno="R002",Marks=40}, new Student{ Name="jerry",Regno="R003",Marks=25}, new Student{ Name="Syed",Regno="R004",Marks=30}, new Student{ Name="Mob",Regno="R005",Marks=70}, }; var objresult = from stu in objStudent let totalMarks = objStudent.Sum(mark => mark.Marks) let avgMarks = totalMarks / 5 where avgMarks > stu.Marks select stu; foreach (var stu in objresult) { Console.WriteLine("Student: {0} {1}", stu.Name, stu.Regno); } Console.ReadLine(); } } |
Program Output
1 2 3 | Student: Bob R002 Student: jerry R003 Student: Syed R004 |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.