Foreach or ForEach<T> Extended Method

Foreach is well known to us and smart enough than for() by reducing the iteration boundary and increment/decrement portion.

Foreach or ForEach<T> Extended Method ?

The choice is your's but let's be one step smarter in the scenerio of looping. Foreach is well known for us and smart enough than for() by reducing the iteration boundary and increment/decrement portion. Let's have a look at list iteration using foreach (we all know that).

namespace consoleEntity

{

    class developer

    {

        public string name { get; set; }

        public void ShowName()

        {

            Console.WriteLine(name);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            List<developer> list = new List<developer>()

            {

                new developer{name="sourav"},

                new developer{name="Sridhar"}

            };

            //Foreach loop

            foreach (developer d in list)

            {

                d.ShowName();

            }

 

            Console.ReadLine();

        }

    }

Cool, it will print all the developer's names from list Collection<T>. In the same scenerio we can use the ForEach() extension method. The signature of the ForEach() extension method is as in the following. If we browse to the List<T> class from the class library then we will find the following screen.

The summary is saying that it performs a specific action on each element of the List<T> class.

And it takes “action” as parameter.

action 

That is reflected here in Visual Studio intellisence when we are trying to invoke the ForEach() extension method of the List<T> collection.

VS intellisence

So, let's implement it in our collection. Here is a sample example.
 

class developer

{

        public string name { get; set; }

        public void ShowName()

        {

            Console.WriteLine(name);

        }

}

class Program

{

    static void Main(string[] args)

    {

        List<developer> list = new List<developer>()

        {

             new developer{name="sourav"},

             new developer{name="Sridhar"}

        };

        //Shorten version of foreach loop

        list.ForEach(O => O.ShowName());

        Console.ReadLine();

    }

}

Expected output

output

Now, let's get to the last point. Is it truy preffered to use the ForEach() extension method rather than a foreach() loop? Depending on the scenerio, if we look closely at the description part of the ForEach() method we will see that it can handle one but only one action, not more than one. Whereas we can invoke multiple actions within a foreach() loop.