Skip to content

Instantly share code, notes, and snippets.

@NickStrupat
Created July 20, 2019 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickStrupat/9667a5ed5d078e9c480a44adc7b2860f to your computer and use it in GitHub Desktop.
Save NickStrupat/9667a5ed5d078e9c480a44adc7b2860f to your computer and use it in GitHub Desktop.
<#@ 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