Multi-dimensional Arrays and IEnumerable
Posted
Tue, May 4 2010 22:19
by
Deborah Kurata
Most of the cool extension methods that you can use with Lambda expressions, such as Where, FirstOrDefault, and Zip, are extensions of the generic IEnumerable<T> class. Interestingly, the .NET multi-dimensional array does not implement the generic IEnumerable<T> class. So you don't have direct access to any of the Linq extension methods.
The reason for this is that a single-dimension array is implemented differently from a multi-dimension array in .NET. This stackoverflow post provides more detail on this issue.
The purpose of this post is to provide a way to work with extension methods on multi-dimensions arrays. The trick is to use Cast.
This example defines a 3x3 array with three student's scores on three exams. It then averages the scores.
In C#:
int[,] multiArray = {{70, 88, 90}, {98, 100, 96}, {88, 94, 95}};
var averageScore = multiArray.Cast<int>().Average();
In VB:
Dim multiArray(,) As Integer = {{70, 88, 90}, {98, 100, 96},
{88, 94, 95}}
Dim averageScore = multiArray.Cast(Of Integer).Average
The first line of code defines the 3 x 3 array.
The second line of code uses the Cast operator to cast the array to a generic IEnumerable(Of Integer). This basically flattens the array into a single set of integers.
Once you have a generic IEnumerable, you can use its associated extension methods, including Average. The result is an average of 91.
Use this technique any time you have to work with multi-dimensional arrays.
Enjoy!