Created
July 20, 2019 03:13
-
-
Save NickStrupat/9667a5ed5d078e9c480a44adc7b2860f to your computer and use it in GitHub Desktop.
This file contains 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
<#@ template debug="false" hostspecific="false" language="C#" #> | |
<#@ assembly name="System.Core" #> | |
<#@ import namespace="System.Linq" #> | |
<#@ import namespace="System.Text" #> | |
<#@ import namespace="System.Collections.Generic" #> | |
<#@ output extension=".cs" #> | |
<# var maxDimensions = 32; #> | |
using System; | |
using System.Collections.Generic; | |
public static class ArrayEnumerableExtensions | |
{ | |
public static IEnumerable<T> AsEnumerable<T>(this Array array) | |
{ | |
if (array is null) | |
throw new ArgumentNullException(nameof(array)); | |
var elementType = array.GetType().GetElementType(); | |
if (elementType != typeof(T)) | |
throw new ArgumentException($"Array element type must match the enumerable type: `{elementType.FullName}` != `{typeof(T).FullName}`", nameof(array)); | |
return array switch | |
{ | |
<# for (var i = 0; i != maxDimensions; i++) { #> | |
T[<#= new String(',', i) #>] a => a.AsEnumerable(), | |
<# } #> | |
_ => throw new ArgumentException("Invalid array rank: " + array.Rank, nameof(array)), | |
}; | |
} | |
<# for (var i = 0; i != maxDimensions; i++) { #> | |
public static IEnumerable<T> AsEnumerable<T>(this T[<#= new String(',', i) #>] array) | |
{ | |
<# for (var j = 0; j != i + 1; j++) { #> | |
for (var _<#= j #> = 0; _<#= j #> != array.GetLength(<#= j #>); _<#= j #>++) | |
<# } #> | |
yield return array[<#= String.Join(", ", Enumerable.Range(0, i + 1).Select(x => "_" + x)) #>]; | |
} | |
<# } #> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment