Last active
May 20, 2018 00:28
-
-
Save kekyo/2e0c456f506ec31431f33741608d5230 to your computer and use it in GitHub Desktop.
How to creation two dimensional array in C#/LINQ.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's a bit more concise version: