mrblah
mrblah

Reputation: 103497

How to loop through a collection that supports IEnumerable?

How to loop through a collection that supports IEnumerable?

Upvotes: 123

Views: 247333

Answers (5)

Luc Bloom
Luc Bloom

Reputation: 1243

You might also try using extensions if you like short code:

namespace MyCompany.Extensions
{
    public static class LinqExtensions
    {
        public static void ForEach<TSource>(this IEnumerable<TSource> source, Action<TSource> actor) { foreach (var x in source) { actor(x); } }
    }
}

This will generate some overhead, for the sake of having stuff inline.

collection.Where(item => item.IsReady).ForEach(item => item.Start());

It becomes even more polished when you have a local or member function that accepts the item type as a parameter:

collection.ForEach(scene.HandleItem);

Upvotes: -1

Alexa Adrian
Alexa Adrian

Reputation: 1858

or even a very classic old fashion method

using System.Collections.Generic;
using System.Linq;
...

IEnumerable<string> collection = new List<string>() { "a", "b", "c" };

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

maybe you would like this method also :-)

Upvotes: 53

Noldorin
Noldorin

Reputation: 147260

Along with the already suggested methods of using a foreach loop, I thought I'd also mention that any object that implements IEnumerable also provides an IEnumerator interface via the GetEnumerator method. Although this method is usually not necessary, this can be used for manually iterating over collections, and is particularly useful when writing your own extension methods for collections.

IEnumerable<T> mySequence;
using (var sequenceEnum = mySequence.GetEnumerator())
{
    while (sequenceEnum.MoveNext())
    {
        // Do something with sequenceEnum.Current.
    }
}

A prime example is when you want to iterate over two sequences concurrently, which is not possible with a foreach loop.

Upvotes: 122

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{

}

Upvotes: 9

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158309

A regular for each will do:

foreach (var item in collection)
{
    // do your stuff   
}

Upvotes: 186

Related Questions