Monday, January 27, 2014

How to loop through a collection that supports IEnumerable?

Whenever you get to this issue, though it seems a really easy job to do here 2 ways how you can iterate on a collection that supports IEnumerable:

First one using a foreach statement:

foreach (var item in collection)
{
    // play with your item
}

I suggest that always when you know your object types of collection to use that type instead of var. I always try to avoid var type. It is something that my team lead advised me and I came to realize it is a good practice.

Then second way to do it is using for statement. Whenever you have a collection and you need to iterate it and according to some conditions some elements might have to be removed you cannot use foreach because you will have a nice error saying: "Collection was modified; enumeration operation may not execute" :) So that is why you need to use for statement.

for(int i = 0; i < collection.Count(); i++) 
{
    string str1 = collection.ElementAt(i);
    // play with your item
}

There might be other ways to iterate, like using GetEnumerator but is enough, for the moment :)
Have a nice day.

No comments:

Post a Comment