public class Node { public Node ChildOf { get; set; } public string Path { get; set; } public IList<Node> Children { get; set; } } public static class Helper { public static Node ArrayToTree(params string[] paths) { Node root = new Node { ChildOf = null, Path = null, Children = new List<Node>() }; foreach (string path in paths) { string[] subPaths = path.Split('.'); Node addTo = root; foreach (string subPath in subPaths) { Node child = addTo.Children.FirstOrDefault(x => x.Path == subPath); if (child == null) { child = new Node { ChildOf = addTo, Path = subPath, Children = new List<Node>() }; addTo.Children.Add(child); }//if addTo = child; }//foreach }//foreach return root; } }
Unit test:
public void TestStructuredData() { Node n = Helper.ArrayToTree( new[] { "Answers", "Answers.Comments", "Answers.Greats", "Answers.Balls.Of.Fire", "Comments" }); Assert.AreEqual(2, n.Children.Count); Assert.AreEqual(3, n.Children[0].Children.Count); Assert.AreEqual("Answers", n.Children[0].Path); Assert.AreEqual("Comments", n.Children[0].Children[0].Path); Assert.AreEqual("Greats", n.Children[0].Children[1].Path); Assert.AreEqual("Balls", n.Children[0].Children[2].Path); Assert.AreEqual("Of", n.Children[0].Children[2].Children[0].Path); Assert.AreEqual("Fire", n.Children[0].Children[2].Children[0].Children[0].Path); Assert.AreEqual("Comments", n.Children[1].Path); }
Avoid stringly-typed programming, use proper data structure.
http://www.google.com/search?q=stringly-typed+programming+-strongly
No comments:
Post a Comment