Skip to content

Instantly share code, notes, and snippets.

@davidehnis
Last active March 27, 2019 14:44
Show Gist options
  • Save davidehnis/2e385b0a1cb7c1d87aafb4b438cbbee2 to your computer and use it in GitHub Desktop.
Save davidehnis/2e385b0a1cb7c1d87aafb4b438cbbee2 to your computer and use it in GitHub Desktop.
How to flatten an array of arbitrarily nested arrays
private void Flatten(object item, List<int> flattened)
{
if (item is int i)
{
flattened.Add(i);
return;
}
if (!(item is List<object> list)) return;
foreach (var itm in list)
{
Flatten(itm, flattened);
}
}
[TestMethod]
public void Flatten_Array()
{
// Arrange
var head = new List<int>();
var first = new List<object> { 1, 2, new List<object> { 3 } };
var second = new List<object> { first, new List<object> { 4 } };
var third = new List<object> { second };
// Act
Flatten(third, head);
// Assert
Assert.IsNotNull(head);
Assert.IsTrue(head.Any());
Assert.AreEqual(4, head.Count);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment