Created
April 29, 2019 11:02
-
-
Save hudo/8d4325a7682c76f38a125ba23a965034 to your computer and use it in GitHub Desktop.
FlattenList
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
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// sample list to test | |
var list = new ArrayList | |
{ | |
new ArrayList { | |
new ArrayList | |
{ | |
new ArrayList | |
{ | |
1, | |
2, | |
new ArrayList { 3 }, | |
4 | |
} | |
}, | |
5 | |
} | |
}; | |
foreach(var item in Flatten(list)) | |
Console.WriteLine(item); | |
} | |
/// <summary> | |
/// Recursive function that flattens list of items | |
/// </summary> | |
/// <param name="list">Array which should contain other ArrayLists or Ints</param> | |
/// <returns>Flattened list of individual items</returns> | |
static IEnumerable<int> Flatten(ArrayList list) | |
{ | |
if (list == null) | |
throw new ArgumentNullException(nameof(list)); | |
foreach (var item in list) | |
{ | |
switch (item) | |
{ | |
case int i: | |
yield return i; | |
break; | |
case ArrayList subList: | |
{ | |
foreach (var subItem in Flatten(subList)) | |
yield return subItem; | |
break; | |
} | |
default: throw new Exception("Provided value needs to be Array or Int"); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment