Getting an enumerator for the entire ArrayList in C#The Enumerators play a vital role in every programming language. Enumerators are used to iterate through collections. Whenever someone declares the collections and stores some values in them, they iterate through the collections to access the values of the collections. These Enumerators will provide a way for sequentially accessing each element in the collection. It can be performed in many ways. Advantages of the Enumerators:Some of the advantages of the Enumerators' uses are as follows:
Using GetEnumerator Method:The ArrayList.GetEnumerator method in C# is used to obtain an enumerator that iterates through the elements of an ArrayList. Syntax:It has the following syntax: This method does not take any parameters. This method will return the IEnumerator interface, which provides a way for iterating through the collection. Example:Let us take an example program to illustrate the GetEnumerator Method in C#. Output: Explanation: This C# program is used to iterate through the array list. Initially, an ArrayList named myArrayList is created, and three strings are inserted. After that, the ArrayList.GetEnumerator method is used to get an enumerator for the entire array list. We can access or iterate through the array list using the enumerator's while loop and MoveNext method. After that, the elements in the myArrayList are printed here. The elements are strings. Using foreach loop:Let us take an example program to iterate through an Array list using a foreach loop in C#. Output: Explanation: In this program, an array list named myArrayList is created to store the elements of type strings. Three strings "India", "America", and "Russia" and added to the array list. After that, a foreach loop is used to access the strings in the array list. This loop automatically utilizes the enumerator of the ArrayList. After that, the elements are printed to the console. The output says that we can also use foreach loop for enumerating through an Array list. Using IEnumerable interface directly:Let us take an example program to iterate through an Array list using an IEnumerable Interface in C#. Output: Explanation: This program also initializes an ArrayList named myArrayList as the above programs. So, by using the Add method, five elements are added to the array list. After that, use the IEnumerable interface directly to obtain an enumerator. A while loop is used to iterate through all the array elements, the MoveNext method is used to get the next element in the array, and the Current is used to get the value in that particular iteration. After that, all the elements in the array are printed. Next TopicMulticast delegates in C# |