Skip to content

Instantly share code, notes, and snippets.

@timabell
Created April 2, 2012 10:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save timabell/2282389 to your computer and use it in GitHub Desktop.
Save timabell/2282389 to your computer and use it in GitHub Desktop.
hierarchy reader from stack overflow
using System.Collections.Generic;
namespace util
{
/// <summary>
/// Storage and parsing of flat string based folder hierarchy.
/// See http://stackoverflow.com/a/8621711/10245
/// </summary>
/// <example><code>
/// NodeEntryCollection cItems = new NodeEntryCollection();
/// cItems.AddEntry(sLine, 0);
/// </code></example>
public class NodeEntryCollection : Dictionary<string, NodeEntry>
{
public NodeEntryCollection()
{
Separator = "/"; // default separator
}
/// <summary>
/// Gets or sets the separator used to split the hierarchy.
/// </summary>
/// <value>
/// The separator.
/// </value>
public string Separator { get; set; }
public void AddEntry(string entry)
{
AddEntry(entry, 0);
}
/// <summary>
/// Parses and adds the entry to the hierarchy, creating any parent entries as required.
/// </summary>
/// <param name="entry">The entry.</param>
/// <param name="startIndex">The start index.</param>
public void AddEntry(string entry, int startIndex)
{
if (startIndex >= entry.Length)
{
return;
}
var endIndex = entry.IndexOf(Separator, startIndex);
if (endIndex == -1)
{
endIndex = entry.Length;
}
var key = entry.Substring(startIndex, endIndex - startIndex);
if (string.IsNullOrEmpty(key))
{
return;
}
NodeEntry item;
if (ContainsKey(key))
{
item = this[key];
}
else
{
item = new NodeEntry { Key = key };
Add(key, item);
}
// Now add the rest to the new item's children
item.Children.AddEntry(entry, endIndex + 1);
}
}
public class NodeEntry
{
public string Key { get; set; }
public NodeEntryCollection Children { get; set; }
public NodeEntry()
{
Children = new NodeEntryCollection();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment