foreach

This should be used when you have a collection.


System.Collections.ArrayList

ArrayList myArrayList = new System.Collections.ArrayList(); 
myArrayList.Add("one");
myArrayList.Add("two");

foreach (string element in myArrayList)
{

}

System.Collections.Generic.List<int>

List<int> myNumbers = new System.Collections.Generic.List<int> { 1, 2, 3, 4, 5 }; 

foreach (int number in myNumbers)
{
    Console.WriteLine(number);
}

Important

If you are iterating through anything that is not a collection (for example an Array) it is more efficient to use a for loop.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext