Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

May 5, 2010

Multi-dimensional Arrays and IEnumerable

Filed under: C#,Lambda Expressions,VB.NET @ 12:19 am

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 3×3 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.


1 Comment

  1.   Shaun — August 21, 2013 @ 10:54 am    Reply

    Thank you, this was a very useful tip in dealing with non IEnumberable Arrays

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2022 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs