using System;
using System.Collections.Generic;
namespace Vanara.Collections
{
/// Represents a node in a .
public class Entry
{
/// Initializes a new instance of the class.
/// The key.
public Entry(string key)
{
Key = key;
}
/// Gets the children of this .
public Hierarchy Children { get; } = new Hierarchy();
/// Gets or sets the key for this .
/// A unique string value.
public string Key { get; }
}
/// Storage and parsing of flat string based folder hierarchy.
///
///
/// Hierarchy cItems = new Hierarchy();
/// cItems.AddEntry(sLine, 0);
///
///
public class Hierarchy : Dictionary
{
/// Gets or sets the separator used to split the hierarchy.
/// The separator.
public string Separator { get; set; } = "\\";
/// Parses and adds the entry to the hierarchy, creating any parent entries as required.
/// The entry.
/// The start index.
public void AddEntry(string entry, int startIndex = 0)
{
if (string.IsNullOrEmpty(entry)) throw new ArgumentNullException(nameof(entry));
if (startIndex >= entry.Length)
return;
var endIndex = entry.IndexOf(Separator, startIndex, StringComparison.InvariantCulture);
if (endIndex == -1)
endIndex = entry.Length;
var key = entry.Substring(startIndex, endIndex - startIndex);
if (string.IsNullOrEmpty(key))
return;
Entry item;
if (ContainsKey(key))
{
item = this[key];
}
else
{
item = new Entry(key);
Add(key, item);
}
// Now add the rest to the new item's children
item.Children.AddEntry(entry, endIndex + 1);
}
}
}