C# IEnumerable Array Example

Array type

IEnumerable works with a 2D array. It enables a foreach-loop over the values in your 2D or jagged array. This results in fewer typo bugs and shorter code. We use IEnumerable and the foreach-loop to loop through all items in a 2D array.

2D Array Examples

Example

Note

This example shows the yield contextual keyword in a method that returns IEnumerable<T>. We can code a IEnumerable generic collection of the values in the two-dimensional grid array. Instead of looping over the array explicitly, we can abstract the loop itself out.

IEnumerable

This C# example program uses the foreach-loop on a 2D array. It implements IEnumerable.

Program that uses yield keyword [C#]

using System;
using System.Collections.Generic;

class Program
{
    static int[,] _grid = new int[15, 15];
    static void Main()
    {
	_grid[0, 1] = 4;
	_grid[4, 4] = 5;
	_grid[14, 2] = 3;
	int r = 0;
	foreach (int v in GridValues())
	{
	    r += v;
	}
	Console.WriteLine(r);
    }
    public static IEnumerable<int> GridValues()
    {
	for (int x = 0; x < 15; x++)
	{
	    for (int y = 0; y < 15; y++)
	    {
		yield return _grid[x, y];
	    }
	}
    }
}

Output

12

Description. The return value is an IEnumerable collection of ints. Because it is a generic type, the type of the IEnumerable return value is in the angle braces.

Int TypeYield keyword

Note on yield keyword. This keyword is one you put before return. It is only used on enumerators, such as this one that returns IEnumerable. You can use it to "save the state" of the function after the return. After the yield is reached, and the value is returned, the foreach loop will call the function again, but you will pick up right where you left off.

Yield Return Example

Foreach loops

Foreach loop construct

One advantage with using foreach loops in the C# language is that foreach eliminates your need to track indexer variables, such as i or x. The code becomes safer and more robust by hiding all the details from the programmers using the array. You can find more information on the foreach-loop construct.

Foreach Loop Examples

Summary

The C# programming language

We looked at how you can transform nested for loops into a foreach loop using the yield keyword. Some complexities in the C# programming language are actually undercover simplifications; I once felt all these syntax flourishes were complete nonsense. It is sometimes useful to combine IEnumerable collections with object-oriented programming.

Interface Types
.NET