Updated February 22, 2023
Introduction to LINQ foreach
LINQ foreach loop is very better in the quick looping process in collections. Foreach loop makes it easy to loop through the collection of items. When retrieving each element in a collection, the LINQ Foreach variable supports well-situated access. It supports all the approaches to retrieve the elements easily; it uses the LINQ extension methods.
Syntax
LINQ foreach loops help to retrieve the collections in a very fast manner easily; let’s see the syntax below,
values.ForEach(val=> Console.WriteLine(val));
Collection of items LINQ-Foreach syntax as follows,
userList.ToList().ForEach(s => Console.WriteLine(u.userName));
How does foreach work in LINQ?
When retrieving each element in a collection, the Foreach variable supports easily accessing data. It supports all the approaches to retrieve the elements easily; it uses the LINQ extension methods. Let’s see a few working flows of LINQ Foreach,
We will use the LINQ Foreach in the Where condition. It executes the list of items when the where condition returns true. Here we included the foreach with the same condition line of code; no need to code in a separate line. It helps to reduce the code and execution time when using Foreach.
var values = new List<int>() { 10, 20, 30, 40, 50 };
values
.Where (val => val > 20)
.ToList()
.ForEach (val=>Console.WriteLine(val));
In the above code, we combine the query condition and foreach loop; it retrieves the elements quickly. In a single line of code, the entire process gets completed. The result will be 30, 40, and 50.
One more process of foreach loop with the conditions where along with contains in it. It combines both the collection and returns the value which contains the same number in both the collection; in a single line of code, we can code the entire process; let’s check the following line of code,
var values_1 = new List<int>() { 100, 200, 300 };
var values_2 = new List<int>() { 200, 500, 700 };
values_1.Where(val => values_2.Contains(val))
.ToList()
.ForEach(val => Console.WriteLine(val));
It returns the result as “200” because the number 200 is presented in both lists.
Examples
Foreach loop makes it easy to loop through the collection of items; let’s see the sample program for a better understanding,
Example #1
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LINQForeach
{
class ProductMaster
{
public int productID { get; set; }
public string productCategory { get; set; }
public string productName { get; set; }
public int productPrice { get; set; }
}
class Program_LINQForeach
{
static void Main(string[] args)
{
// building the product class List
IList<ProductMaster> product_ItemList = new List<ProductMaster>();
product_ItemList.Add(new ProductMaster { productID = 1005, productCategory = "Pantry", productName = "Biscuits", productPrice = 20 });
product_ItemList.Add(new ProductMaster { productID = 1006, productCategory = "Pantry", productName = "Dates", productPrice = 60 });
product_ItemList.Add(new ProductMaster { productID = 1007, productCategory = "Pantry", productName = "Honey", productPrice = 110 });
product_ItemList.Add(new ProductMaster { productID = 1008, productCategory = "Pantry", productName = "Chips", productPrice = 35 });
product_ItemList.Add(new ProductMaster { productID = 1009, productCategory = "Stationery", productName = "A4 Sheet Bunddle", productPrice = 100 });
product_ItemList.Add(new ProductMaster { productID = 1010, productCategory = "Stationery", productName = "Pencil Box", productPrice = 52 });
product_ItemList.Add(new ProductMaster { productID = 1011, productCategory = "Stationery", productName = "Ink-Bottle", productPrice = 45 });
product_ItemList.Add(new ProductMaster { productID = 1012, productCategory = "Stationery", productName = "NoteBooks", productPrice = 75 });
Console.WriteLine("\nLINQ FOREACH LOOP");
Console.WriteLine("\n-----------------");
Console.WriteLine("\nProduct ID\tProduct Name");
Console.WriteLine("\n----------\t-------------- \n");
product_ItemList.Where(p => p.productCategory.StartsWith("P"))
.ToList()
.ForEach(p => Console.WriteLine("\n" + p.productID+"\t\t"+p.productName));
Console.WriteLine("\n----------\t-------------\n");
Console.ReadKey();
}
}
}
In the above code, we have to retrieve the product list with starting letter of the product category “P,”
product_ItemList.Where(p => p.productCategory.StartsWith("P"))
.ToList()
.ForEach(p => Console.WriteLine("\n" + p.productID+"\t\t"+p.productName));
In the list, the Product category begins with the letter ‘P’ is Pantry, so the items listed under the pantry categories with product id and product name. Let’s see the below output as follows.
Output:
Example #2
In this sample program, we used multiple actions performed with Foreach loop, like to display the Employee details with employee name starting letter begins with ‘R’ and their salary must be above 40000 with age limit should be less than 25 and order the list using Orderby method with employee name let’s see the program for better understanding,
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Console_LINQForeach
{
class Program_LINQ_ForEach
{
public class EmployeeMaster
{
public int eID
{ get; set; }
public string eName
{ get; set; }
public string eQuali
{
get;
set;
}
public int eSalary { get; set; }
public int deptID { get; set; }
public int eAge { get; set; }
public static List<EmployeeMaster> Get_Employees()
{
return new List<EmployeeMaster>()
{
new EmployeeMaster() {eID = 1000, eName = "Joseph",deptID=1,eQuali = "MCA", eAge=21,eSalary=25000},
new EmployeeMaster() {eID = 1005, eName = "Rithick", deptID=2,eQuali = "B.E",eAge=23, eSalary=47000},
new EmployeeMaster() {eID = 1001, eName = "Sara",deptID=1,eQuali = "MCA",eAge=21, eSalary=60000},
new EmployeeMaster() {eID = 1007, eName = "Rio",deptID=3, eQuali = "B.E",eAge=27,eSalary=35000},
new EmployeeMaster() {eID = 1003, eName = "David",deptID=1, eQuali = "M.Sc",eAge=21, eSalary=30000},
new EmployeeMaster() {eID = 1004, eName = "Remo",deptID=3, eQuali = "B.E",eAge=24, eSalary=52000},
};
}
}
static void Main(string[] args)
{
Console.WriteLine("\nLINQ_Foreach with Multiple Actions");
Console.WriteLine("----------------------------------\n");
Console.WriteLine("\nDisplaying Employee with Starting Letter 'R', Salary above 40000,\nAge Criteria and OrderBy Method\n");
Console.WriteLine("\t\tDepartment ID\tEmployee Name\tEmployee Salary");
Console.WriteLine("\t\t-------------\t-------------\t---------------\n");
EmployeeMaster.Get_Employees()
.Where(emp => emp.eName
.StartsWith("R") && emp.eSalary > 40000 && emp.eAge<25)
.OrderBy(emp=>emp.eName)
.ToList()
.ForEach(emp => Console.WriteLine("\t\t"+emp.deptID+"\t\t"+emp.eName +"\t\t" + emp.eSalary));
Console.WriteLine("\t\t-------------\t--------------\t---------------\n");
Console.ReadKey();
}
}
}
In this code, we used the loop with several actions performed with use where condition, order by the method as follows,
EmployeeMaster.Get_Employees()
.Where(emp => emp.eName
.StartsWith("R") && emp.eSalary > 40000 && emp.eAge<25)
.OrderBy(emp=>emp.eName)
.ToList()
.ForEach(emp => Console.WriteLine("\t\t"+emp.deptID+"\t\t"+emp.eName +"\t\t" + emp.eSalary));
In a single line of code, we performed multiple actions, which helped to reduce the coding lines and see the below output for clear perceptive.
Output:
Conclusion
In this article, we have seen the usage of the LINQ-Foreach loop programmatically. LINQ Foreach is used to retrieve the values quickly; using this method; we can easily code our program, which helps reduce the coding lines. Hope the article helps to understand the usage of Foreach.
Recommended Articles
This is a guide to LINQ foreach. Here we discuss the usage of the LINQ-Foreach loop programmatically with examples and outputs. You may also have a look at the following articles to learn more –