/// <summary> /// Travel nodes by the key elements<br/> /// 根据键里的元素探索节点<br/> /// </summary> /// <param name="key">Key elements</param> /// <param name="createChildsIfNotExist">Create child node if not exist</param> /// <returns></returns> public IEnumerable <HierarchyDictionary <TKeyElement, TValue> > Travel( IEnumerable <TKeyElement> key, bool createChildsIfNotExist) { var node = this; yield return(node); foreach (var element in key) { if (node.Childs == null || !node.Childs.TryGetValue(element, out var childNode)) { if (createChildsIfNotExist) { if (node.Childs == null) { node.Childs = new Dictionary <TKeyElement, HierarchyDictionary <TKeyElement, TValue> >(); } childNode = new HierarchyDictionary <TKeyElement, TValue>(element, node); node.Childs[element] = childNode; } else { break; } } node = childNode; yield return(node); } }
/// <summary> /// Travel nodes by the key elements, return the last node if found or created<br/> /// 根据键里的元素探索节点, 返回找到或者创建的最后一个节点<br/> /// </summary> /// <param name="key">Key elements</param> /// <param name="createChildsIfNotExist">Create child node if not exist</param> /// <returns></returns> public HierarchyDictionary <TKeyElement, TValue> TravelLast( IEnumerable <TKeyElement> key, bool createChildsIfNotExist) { var node = this; foreach (var element in key) { if (node.Childs == null || !node.Childs.TryGetValue(element, out var childNode)) { if (createChildsIfNotExist) { if (node.Childs == null) { node.Childs = new Dictionary <TKeyElement, HierarchyDictionary <TKeyElement, TValue> >(); } childNode = new HierarchyDictionary <TKeyElement, TValue>(element, node); node.Childs[element] = childNode; } else { #pragma warning disable S1168 return(null); #pragma warning restore S1168 } } node = childNode; } return(node); }
/// <summary> /// Initialize with parent node<br/> /// 指定上级节点的初始化<br/> /// </summary> public HierarchyDictionary(TKeyElement keyElement, HierarchyDictionary <TKeyElement, TValue> parent) { KeyElement = keyElement; Parent = parent; }