Skip to content

Instantly share code, notes, and snippets.

@cirocorvino
Last active February 6, 2024 10:48
Show Gist options
  • Save cirocorvino/da37066c5de47b6fd0f5ab70707e82a4 to your computer and use it in GitHub Desktop.
Save cirocorvino/da37066c5de47b6fd0f5ab70707e82a4 to your computer and use it in GitHub Desktop.
Flatten Array on .Net Fiddler version
using System;
using System.Collections.Generic;
using System.Text;
//see at link: https://dotnetfiddle.net/5HGX96
namespace FlattenArrayExample
{
public static class Program
{
public static void Main()
{
//arrange
#region arrange section
#region jagged array sample
int[][] jaggedArray;
jaggedArray = new int[3][];
jaggedArray[0] = new int[1];
jaggedArray[1] = new int[2];
jaggedArray[2] = new int[3];
jaggedArray[0][0] = 1;
jaggedArray[1][0] = 2;
jaggedArray[1][1] = 3;
jaggedArray[2][0] = 4;
jaggedArray[2][1] = 5;
jaggedArray[2][2] = 6;
#endregion jagged array sample
#region nested array sample
object[][] nestedArray;
nestedArray = new object[3][];
nestedArray[0] = new object[1];
nestedArray[1] = new object[2];
nestedArray[2] = new object[3];
nestedArray[0][0] = new object[] { 4,5,6, new object[3] { 6,7,8} };
nestedArray[1][0] = 2;
nestedArray[1][1] = 3;
nestedArray[2][0] = 4;
nestedArray[2][1] = 5;
nestedArray[2][2] = 6;
#endregion nested array sample
#endregion
//act
//var flattenedArray = ArrayUtils.GetFlattenedIntArray(jaggedArray);
var flattenedArray = ArrayUtils.GetFlattenedIntArray(nestedArray);
//check
if (flattenedArray != null)
{
var flattenedArraySerialized = new StringBuilder();
foreach (var el in flattenedArray)
{
flattenedArraySerialized.Append(string.Format("{0},",el));
}
Console.WriteLine(string.Format("flattened array -> [{0}]", flattenedArraySerialized));
}
Console.ReadLine();
}
}
public static class ArrayUtils
{
public static int[] GetFlattenedIntArray(object jaggedArray)
{
var flattenedArray = new List<int>();
var jaggedArrayType = jaggedArray.GetType();
var expectedType = typeof(int);
if (jaggedArrayType.IsArray)
{
if (expectedType.IsAssignableFrom(jaggedArrayType.GetElementType()))
{
foreach (var el in jaggedArray as int[])
{
flattenedArray.Add(el);
}
}
else
{
foreach (var el in jaggedArray as object[])
{
foreach (var retIntEl in GetFlattenedIntArray(el))
{
flattenedArray.Add(retIntEl);
}
}
}
}
else if (jaggedArrayType == expectedType)
{
flattenedArray.Add((int)jaggedArray);
}
else
{
return new int[0];
}
return flattenedArray.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment