Skip to content

Instantly share code, notes, and snippets.

@X4
Last active December 19, 2015 11:49
Show Gist options
  • Select an option

  • Save X4/5950285 to your computer and use it in GitHub Desktop.

Select an option

Save X4/5950285 to your computer and use it in GitHub Desktop.
Converting example using yield and the iterator approach to a basic loop or using LINQ.
// Your current code
public static IEnumerable<T> Flatten<T>(this T[,] matrix)
{
var rows = matrix.GetLength(0);
var cols = matrix.GetLength(1);
for (var i = 0; i < rows;i++ )
{
for (var j = 0; j < cols; j++ )
yield return matrix[i, j];
}
}
// Without yield, using LINQ
// @see http://de.wikipedia.org/wiki/LINQ
int[,] array2d = ...;
var array1d = array2d.Cast<int>().ToArray();
// Without yield, general solution
int[,] array2d = ...;
var rows = array2d.GetLength(0);
var cols = array2d.GetLength(1);
var array1d = new int[rows * cols];
var current = 0;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array1d[current++] = array2d[i, j];
}
}
// Without yield, shortest solution
int[,] array2d = ...;
var array1d = new int[array2d.GetLength(0) * array2d.GetLength(1)];
var current = 0;
foreach (var value in array2d)
{
array1d[current++] = value;
}
// Usage:
int[,] array2D = new int[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[] array1D = array2D.Flatten().ToArray();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment