Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kekyo/2e0c456f506ec31431f33741608d5230 to your computer and use it in GitHub Desktop.
Save kekyo/2e0c456f506ec31431f33741608d5230 to your computer and use it in GitHub Desktop.
How to creation two dimensional array in C#/LINQ.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace ConsoleApplication21
{
static class Program
{
public static T[,] ToTwoDimensionalArray<T>(this IEnumerable<IEnumerable<T>> enumerable)
{
var lines = enumerable.Select(inner => inner.ToArray()).ToArray();
var columnCount = lines.Max(columns => columns.Length);
var twa = new T[lines.Length, columnCount];
for (var lineIndex = 0; lineIndex < lines.Length; lineIndex++)
{
var line = lines[lineIndex];
for (var columnIndex = 0; columnIndex < line.Length; columnIndex++)
{
twa[lineIndex, columnIndex] = line[columnIndex];
}
}
return twa;
}
static void Main(string[] args)
{
var r = new Random();
var results = Enumerable.Range(0, 100).
Select(lineIndex => Enumerable.Range(0, 300).
Select(columnIndex => r.Next())).
ToTwoDimensionalArray();
Debug.Assert(results.GetLength(0) == 100);
Debug.Assert(results.GetLength(1) == 300);
}
}
}
@lex57ukr
Copy link

lex57ukr commented Sep 7, 2017

Here's a bit more concise version:

static class EnumerableExtensions
{
    public static T[,] To2DArray<T>(this IEnumerable<IEnumerable<T>> source)
    {
        var data = source
            .Select(x => x.ToArray())
            .ToArray();

        var res = new T[data.Length, data.Max(x => x.Length)];
        for (var i = 0; i < data.Length; ++i)
        {
            for (var j = 0; j < data[i].Length; ++j)
            {
                res[i,j] = data[i][j];
            }
        }

        return res;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment