Last active
March 27, 2019 14:44
-
-
Save davidehnis/2e385b0a1cb7c1d87aafb4b438cbbee2 to your computer and use it in GitHub Desktop.
How to flatten an array of arbitrarily nested arrays
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
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