Introduction
Here, we are going to see the uses of the Into and Let keywords in LINQ and we also will discuss their differences. Both keywords are helpful when playing with a set of object collections. Let's move to the detailed explanation.
Prerequisites
- Visual Studio
- Basic knowledge of LINQ
Article Flow
- Use of Into Keyword
- Use of Let Keyword
- Difference between into and Let keyword
Uses of Into
The Into keyword allows us to create a temporary variable to store the results of a group, join, or select clause into a new variable. Before moving on this, let's create a sample project. For this, I have created two classes and added dummy values in those.
- public class Employee {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public string Designation {
- get;
- set;
- }
- public int YOE {
- get;
- set;
- }
- }
- public class Salary {
- public int EmpID {
- get;
- set;
- }
- public double MonthSalary {
- get;
- set;
- }
- }
- class LinqSample {
- static void Main(string[] args) {
- List < Employee > empList = new List < Employee > ();
- empList.Add(new Employee {
- Id = 1, Name = "Gnanavel Sekar", Designation = "Software Engineer", YOE = 3
- });
- empList.Add(new Employee {
- Id = 2, Name = "Subash S", Designation = "Software Developer", YOE = 2
- });
- empList.Add(new Employee {
- Id = 3, Name = "Robert B", Designation = "Application Developer", YOE = 3
- });
- empList.Add(new Employee {
- Id = 4, Name = "Ammaiyappan k", Designation = "Software Engineer", YOE = 3
- });
- Console.WriteLine("Employee List");
- foreach(var employee in empList) {
- Console.WriteLine("ID:" + employee.Id + ", Name: " + employee.Name + ", Designation :" + employee.Designation + ", Year of Exp: " + employee.YOE);
- }
- List < Salary > salaryDetails = new List < Salary > ();
- salaryDetails.Add(new Salary {
- EmpID = 1, MonthSalary = 80000
- });
- salaryDetails.Add(new Salary {
- EmpID = 2, MonthSalary = 70000
- });
- salaryDetails.Add(new Salary {
- EmpID = 3, MonthSalary = 50000
- });
- salaryDetails.Add(new Salary {
- EmpID = 4, MonthSalary = 80000
- });
- Console.WriteLine(Environment.NewLine + "Salary Details");
- foreach(var salary in salaryDetails) {
- Console.WriteLine("Employee Id: " + salary.EmpID + ", Salary :" + salary.MonthSalary);
- }
- }
- }
Okay, now we see the clear list of employees and their respective salary.
Now, let us move into this concept by using these lists. First, make a simple example for easy understanding.
- var newEmployeeList = from e in empList
- group e by new {
- e.YOE, e.Designation
- }
- into gEmployee
- where gEmployee.Count() > 1
- select new {
- gEmployee.Key.YOE, gEmployee.Key.Designation, totalemplcount = gEmployee.Count()
- };
- Console.WriteLine("New Grouped Employee List");
- foreach(var emp in newEmployeeList) {
- Console.WriteLine("Designation : " + emp.Designation + ", Year of Emp : " + emp.YOE + ",Total Employee in this Group : " + emp.totalemplcount);
- }
Detailed Description
- from e in empList -> we are assigning all collection values into the group e
- group e by new{e.YOE, e.Designation} -> this group keyword is used to put the collection into one container of similar things with satified conditions, here we are grouping the employee by YOE (year of exp.,) and designation
- into gEmployee -> grouped list or collection of values stored in temporary variable of gEmployee by using the into keyword where gEmployee.Count() > 1 -> Here, we are checking whether the grouped collection has more than one element.
- select new { gEmployee.Key.YOE, gEmployee.Key.Designation, totalemplcount = gEmployee.Count() }; -> if more than one element exists in the temporary variable of collection, we proceed to select the value from that respective collection. Here, we are saying to select YOE, Designation, and total employee count in that respective group.
For ease of understanding, I have provided an image below.
To get more clear view, let's see another example.
- var newEmployeeSalary = (from t1 in empList join t2 in salaryDetails on t1.Id equals t2.EmpID group t2 by new {
- t2.MonthSalary
- }
- into g select new {
- g.Key.MonthSalary
- }).ToList();
- Console.WriteLine("New EmployeeList with Salary");
- foreach(var empsal in newEmployeeSalary) {
- Console.WriteLine("Salary : " + empsal.MonthSalary);
- }
Detailed Description
- from t1 in empList -> we are assigning the emplist collection to t1
- join t2 in salaryDetails on t1.Id equals t2.EmpID -> same salary details are in t2 on making join by comparing both table employee id
- group t2 by new { t2.MonthSalary } -> here we are grouping the collection by monthsalary
- into g-> once the grouping is done we put all grouped values in the container named g
- select new { g.Key.MonthSalary }).ToList(); -> finally we are selecting the salarydetails from that container and representing this as list
Now, run this code and see the result. In the below result, we can see the 3 rows while we have 4 rows in the original list because the salary 80000 occurs twice and it's grouped as 1.
Uses of Let
Let keyword allow us to store the result of the query which can be used in subsequent queries; i.e., it creates a new variable and initializes it with the result of the expression you supply.
See the example:
- var letsal = (from e in salaryDetails
- let yourlogic = 60000
- where e.MonthSalary < yourlogic select e).ToList();
- Console.WriteLine("New EmployeeList with Let Keyword");
- foreach(var empsal in letsal) {
- Console.WriteLine("Emp Id:" + empsal.EmpID, "Emp Salary : " + empsal.MonthSalary);
- }
Detailed Description
- from e in salaryDetails -> here we are binding all salary details in the name of e
- let yourlogic = 60000 -> here we can perform our own logic and here I mentioned static value as 60000 to that let variable
- where e.MonthSalary < yourlogic -> now am filtering the salarydetails whichever < (greater than) yourlogic variable
Now, let's see the result to get more knowledge about this.
Now, let's see some logic statement with let variable.
- string[] mySkills = {
- "Asp.net",
- "MVC",
- "Linq",
- "Docusign",
- "EntityFramework",
- "Jquery",
- "C#",
- "SqlServer",
- "Orchard-CMS"
- };
- var skillandrank = from skills in mySkills
- let skill = OurLogic(skills)
- let rank = RankSkill(skill)
- select new {
- skill,
- rank
- };
- Console.WriteLine("Let Keyword with Some Logics");
- foreach(var item in skillandrank) {
- Console.WriteLine("Skill : " + item.skill + ", Rank : " + item.rank);
- }
- static string RankSkill(string value) {
- switch (value) {
- case "Asp.net":
- case "MVC":
- case "Linq":
- return "Top 3";
- case "Docusign":
- case "EntityFramework":
- case "Jquery":
- return "Top 6";
- case "C#":
- case "SqlServer":
- case "Orchard-CMS":
- return "Top 10";
- default:
- return "Not in Rank";
- }
- }
- static string OurLogic(string value) {
- switch (value) {
- case "Asp.net":
- case "MVC":
- case "Linq":
- case "Docusign":
- case "EntityFramework":
- case "Jquery":
- case "C#":
- case "SqlServer":
- case "Orchard-CMS":
- return value;
- default:
- return "Other's";
- }
- }
Detailed Description
- from skills in mySkills-> we are calling all skills in the name of skill variable
- let skill = OurLogic(skills) -> each time it's executed for each skill it will return the skill name and it's stored in skill variable(let)
- let rank = RankSkill(skill) -> this is also executed for each skill and it will return the rank for each skill and it's stored in rank variable(let)
- select new { skill, rank }; -> finally the let variable values are selected by using select new.
Okay, now we will see the result to get clear picture of this concept.
Now, let's get into more details about these two.
Differences between Into and Let keyword
Most people find it difficult to decide which one to use when designing a LINQ query.
Let | Into |
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. ex: var skillandrank = from skills in mySkills let skill = OurLogic(skills) let rank = RankSkill(skill) select new { skill, rank }; | Hides the previous variable when used in a query, as you see in the above example, which means it hides the previous range variable and creates a temporary range variable which you can use in further operations . ex: var newEmployeeList = from e in empList group e by new { e.YOE, e.Designation } into gEmployee where gEmployee.Count() > 1 select new { gEmployee.Key.YOE, gEmployee.Key.Designation, totalemplcount = gEmployee.Count() }; |
Like var, a let variable has an implicit type. We can resuse the variable in subsequent statement(query) so that we can avoid more dublicate work as well as we can easily handle the complex query | It holds the value in temporary variable as collection but not in subsequent statement(query), it will make us write dublicate query. |
Summary
In this article, we learned how to use the Let and Into keywords in LINQ query. I hopw now you have a clear picture of both the keywords and their differences.
Let
This keyword is a part of a query expression. It introduces a variable. We can, then, reuse the variable elsewhere in the query.
Into
The Into contextual keyword can be used to create a temporary identifier to store the results of a group, join or select clause into a new identifier. This identifier can itself be a generator for additional query commands.
I hope you enjoyed this article and your valuable feedback is always welcome.