03 Tired of for(int i = 0; i != array.Length; ++i)?

Foreach() usually helps iterating over an array, but what if the indices are required? The recurring pattern of ‘for(int i=0; i != length; ++i)’ or similar variants are repeatedly used over and over again. Wish I could use something like foreach().

With the following Array extension method, you can:

public static IEnumerable<int> indices(this Array a)
{
  int l = a.Length;
  for (int i = 0; i != l; ++i)
    yield return i;
}

Now instead of:

for(int i=0; i != someArray.Length; ++i)
{
}

you may use:

foreach(var i in someArray.indices())
{
}

which looks a lot smarter :)

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Another way

public static void ForEach<T>(this IEnumerable<T> source, Action<T, int> action)
{
int count = 0;

foreach (T item in source)
action(item, count++);
}

nice!

Indeed nice! And the value is available to the delegate, too!