- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get an enumerator that iterates through Collection in C#
To get an enumerator that iterates through Collection, the code is as follows −
Example
using System; using System.Collections.ObjectModel; public class Demo { public static void Main(){ Collection<string> col = new Collection<string>(); col.Add("Andy"); col.Add("Kevin"); col.Add("John"); col.Add("Kevin"); col.Add("Mary"); col.Add("Katie"); col.Add("Barry"); col.Add("Nathan"); col.Add("Mark"); Console.WriteLine("Count of elements = "+ col.Count); Console.WriteLine("Iterating through the collection..."); var enumerator = col.GetEnumerator(); while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } } }
Output
This will produce the following output −
Count of elements = 9 Iterating through the collection... Andy Kevin John Kevin Mary Katie Barry Nathan Mark
Example
Let us see another example −
using System; using System.Collections.ObjectModel; public class Demo { public static void Main(){ Collection<int> col = new Collection<int>(); col.Add(100); col.Add(200); col.Add(300); col.Add(400); col.Add(500); Console.WriteLine("Count of elements = "+ col.Count); Console.WriteLine("Iterating through the collection..."); var enumerator = col.GetEnumerator(); while (enumerator.MoveNext()) { Console.WriteLine(enumerator.Current); } } }
Output
This will produce the following output −
Count of elements = 5 Iterating through the collection... 100 200 300 400 500
Advertisements