Last active
May 7, 2016 22:49
-
-
Save complxalgorithm/a621b36b7e0daa836a0c25043279b54d to your computer and use it in GitHub Desktop.
A method to flatten an array using C# (using an example).
This file contains hidden or 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
public static class Ex { | |
public static List<object> Flatten(this List<object> list) { | |
var result = new List<object>(); | |
foreach (var item in list) { | |
if (item is List<object>) { | |
result.AddRange(Flatten(item as List<object>)); | |
} else { | |
result.Add(item); | |
} | |
} | |
return result; | |
} | |
public static string Join<T>(this List<T> list, string glue) { | |
return string.Join(glue, list.Select(i => i.ToString()).ToArray()); | |
} | |
} | |
class Program { | |
// Using example [[1,2,[3]],4] -> [1,2,3,4] | |
static void Main(string[] args) { | |
var list = {new List<object>{new List<object>{1, 2, new List<object>{new List<object>{3}}}, 4}}; | |
Console.WriteLine("[" + list.Flatten().Join(", ") + "]"); | |
Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment