내가이 접근 할 방법은 다음과 같습니다
요소의 중첩 된 계층 구조를 (자세한 내용이 필요한 경우이 나중에 확장 할 수 있습니다) 개최 클래스와 컬렉션을 만듭니다.
string[] asLines;
// ToDo: Add code here to populate the collection of lines to process
// Create a base element that makes popuplation of the elements easier
Element BaseElement = new Element("");
// Cycle through each of the lines
foreach (string sLine in asLines())
{
// Get the components out of the line
string[] asElements = sLine.Split("|");
// Starting with the base element
Element oParentElement = BaseElement;
// Cycle through each of the elements that were found, adding the current value to the parent's
// collection of children, then using the new or found item as the parent for the next item in the list
for (int nI = 0; nI < asElements.Length; nI++)
{
oParentElement = oParentElement.AddOrFetchChild(asElements[nI]);
}
}
// Finally, add the nodes to the tree recursively
AddNodesToTree(BaseElement.Children, this.treeView1.Nodes);
을이 재귀 방법 :
public class Element
{
public Element(string Name)
{
this.Name = Name;
}
public string Name { get; set; }
public ElementCollection Children = new ElementCollection();
// This method is used to add the specified child name if it does not currently
// exist, or return the existing one if it does
public Element AddOrFetchChild(string sName)
{
Element oChild;
if (this.Children.ContainsKey(sName))
{
oChild = this.Children[sName];
}
else
{
oChild = new Element(sName);
this.Children.Add(sName, oChild);
}
return oChild;
}
}
public class ElementCollection : System.Collections.Generic.Dictionary<string, Element>
{
}
그리고 (이 코드를 수정할 필요없이 레코드 구조에 중첩의 수준을 지원 않습니다) 컬렉션으로 데이터를 구문 분석 문자열의 모든 데이터와 IEnumerable<string>
를 반환하는 GetData()
기능을 감안할 때 트리
/// <summary>
/// A recursive method to add all of the records to the specified collection of nodes
/// </summary>
/// <param name="cRecords"></param>
/// <param name="cNodes"></param>
private void AddNodesToTree(ElementCollection cRecords, TreeNodeCollection cNodes)
{
foreach (Element oRecord in cRecords.Values)
{
TreeNode oNode = new TreeNode();
oNode.Text = oRecord.Name;
oNode.Tag = oRecord;
cNodes.Add(oNode);
// Now add the node's children if any
if (oRecord.Children.Count != 0)
{
AddNodesToTree(oRecord.Children, oNode.Nodes);
}
}
}
"Newyork"과 "New York"이 실제로 찾고있는 솔루션의 한 노드에 일치합니까? – Jay
opps..spell correct –