Sunday, August 28, 2016

Can Foreach Loop iterates backwards??

Technically speaking the answer is NO, Foreach loop is meant for iterating the list what ever you pass on to it. But to execute the list in backwards using forloop we have different approaches one of the approach is below..

In C# we have Reverse() function which will reverse the list of elements.
Call Reverse() on the list.
Now, iterate using foreach loop that's it your job is doe.

Example:

Class Program
    {
        static void Main(string[] args)
        {
           List<string>  objList =  new List<string>();
           objList.Add("1");
           objList.Add("2");
           objList.Add("3");
         
           objList.Reverse();


           foreach (string obj in objList)
            {
            Console.WriteLine(str.ToString());
             }
    }
Note: This is not efficient way to iterate the list in backwards.

No comments:

Post a Comment