about Collections


T

Tony Johansson

Hi!

The ArrayList support the ICollection and IEnumerable.
Below is three ways to iterate through a collection of an instance of an
ArrayList object.
I just find it's easier to iterate though a collection by using the for loop
or the foreach so my question is
when is it better or more appropriate to use the Enumerator.

static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(1);
list.Add("hej");

//Using the foor loop
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list);
}

//Using the foreach loop
foreach (object i in list)
{
Console.WriteLine(i);
}

//Using the Enumerator
IEnumerator enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}

//Tony
 
Ad

Advertisements

G

Göran Andersson

Tony said:
Hi!

The ArrayList support the ICollection and IEnumerable.
Below is three ways to iterate through a collection of an instance of an
ArrayList object.
I just find it's easier to iterate though a collection by using the for loop
or the foreach so my question is
when is it better or more appropriate to use the Enumerator.

static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(1);
list.Add("hej");

//Using the foor loop
for (int i = 0; i < list.Count; i++)
{
Console.WriteLine(list);
}

//Using the foreach loop
foreach (object i in list)
{
Console.WriteLine(i);
}

//Using the Enumerator
IEnumerator enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}

//Tony


The foreach loop is using the enumerator. Using the enumerator yourself
might be useful if you for example are looping through two collections
in parallel.

Note: Unless you are stuck with framework 1, you shouldn't use the
ArrayList class any more. Use the strongly typed List<T> class instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top