ForEach Method for the collections

dhirenkaunar-15094
Posted by dhirenkaunar-15094 under C# category on | Points: 40 | Views : 1737
In this post I am going to discuss about the new method introduce in the .net framework ForEach which allow to perform the action on the each set of element.

Syntax

public void ForEach(Action action)
Action is delegate or function to perform on each element of the List.
To get in more detail how it works check check the following code.
Below is Employee class which has property related to employee of the company.

public class Employee
{
public string Name { get; set; }
public int Salary { get; set; }
public string Address { get; set; }
public int Id { get; set; }
}
and now in following line of code I am initializing list of employees

class Program
{
static void Main(string[] args)
{
List emplst = new List {
new Employee() { Name="Manas", Address = "Odisa", Id=1, Salary=2012},
new Employee() { Name="Hemant", Address = "Ahmedabad", Id=2, Salary=2348},
new Employee() { Name="Jyoti", Address = "Odisa", Id=3, Salary=8999},
new Employee() { Name="Hina", Address = "Ahmedabad", Id=4, Salary=7888}
};
Now I want to increase salary of each employee by 20%, so with the the help of new ForEach construct I can easily achieve it by using following line of code.

emplst.ForEach(new Program().incSalary);
private void incSalary(Employee emp)
{
emp.Salary += (emp.Salary * 20)/100;
}
}

As you can see in above code I have written new Program().incSalary as action, in the incsalary method as you see I increase the salary of each employee 10%.
This thing can easily also done by making use of the foreach loop available but if you see the the ForEach in reflector it does the same thing.

#Example :

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
List names = new List();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");

// Display the contents of the list using the Print method.
names.ForEach(Print);

// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(String name)
{
Console.WriteLine(name);
});
}

private static void Print(string s)
{
Console.WriteLine(s);
}
}
/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/

Comments or Responses

Login to post response