CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
namespace Demo
{
public static class Program
{
public static void Main()
{
var matrix = new string[5, 10];
for (int row = 0; row < matrix.GetLength(0); ++row)
{
for (int col = 0; col < matrix.GetLength(1); ++col)
{
matrix[row, col] = $"{row}, {col}";
}
}
var col3 = new ArrayColumn<string>(matrix, column: 3); // Grab column 3
for (int col = 0; col < col3.Count; ++col)
{
Console.WriteLine(col3[col]);
}
Console.WriteLine("-----------------");
foreach (var element in col3)
{
Console.WriteLine(element);
}
}
}
public sealed class ArrayColumn<T>: IReadOnlyList<T>
{
public ArrayColumn(T[,] matrix, int column)
{
_matrix = matrix;
_column = column;
Count = _matrix.GetLength(0);
}
public IEnumerator<T> GetEnumerator()
{
IEnumerable<T> items()
{
for (int row = 0; row < Count; ++row)
{
yield return _matrix[row, _column];
}
}
return items().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public int Count { get; }
public T this[int index] => _matrix[index, _column];
readonly T[,] _matrix;
readonly int _column;
}
}