Created
October 31, 2014 07:20
-
-
Save thesid/e44feff716edad01b602 to your computer and use it in GitHub Desktop.
Convert Flat string list to hierarchical object using C#
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication1 | |
{ | |
public static class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var forumLib = new List<string> | |
{ | |
"Offices_Pune", | |
"Offices_Pune_HR", | |
"Offices_Pune_PMO", | |
"Offices_London", | |
"Offices_London_DEV", | |
"Offices_London_DEV_DOTNET", | |
"Offices_London_DEV_JAVA", | |
"Offices_London_QA", | |
"Offices_Mumbai", | |
"Finances", | |
"Sales", | |
"HR", | |
"Sales_Training" | |
}; | |
Node n = new Node(); | |
foreach (var nodepath in forumLib) | |
{ | |
n.AddPath(nodepath); | |
} | |
} | |
public static void AddPath(this Node sourceNode, string path) | |
{ | |
char[] charSeparators = new char[] { '_' }; | |
string[] parts = path.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries); | |
Node current = sourceNode; | |
foreach (string part in parts) | |
{ | |
Node child; | |
if (!current._nodes.TryGetValue(part, out child)) | |
{ | |
child = new Node | |
{ | |
Path = part | |
}; | |
current._nodes[part] = child; | |
} | |
current = child; | |
} | |
} | |
} | |
public class Node | |
{ | |
public readonly IDictionary<string, Node> _nodes = | |
new Dictionary<string, Node>(); | |
public string Path { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment