Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

ForEach Method for the collections

DZone's Guide to

ForEach Method for the collections

·
Free Resource
In this small 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<t> action)
Action<t> 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<employee> emplst = new List<employee> { 
          new Employee() { Name="pranay", Address = "Ahmedabad", Id=1, Salary=1234},
          new Employee() { Name="Hemang", Address = "Ahmedabad", Id=2, Salary=2348},
          new Employee() { Name="kurnal", Address = "Himmatnagar", Id=3, Salary=8999},
          new Employee() { Name="Hanika", Address = "Ahmedabad", Id=4, Salary=7888}
        };
Now I want to increase salary of each employee by 10%, 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 * 10)/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.
ForEach method make code more simple and easy to understand.
Topics:

Published at DZone with permission of Pranay Rana, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}