2011-12-14 1 views
0

문자열을 folowing하여 트리 뷰 컨트롤을 준비하려고합니다.은 문자열 컬렉션을 사용하여 트리 뷰 컨트롤을 만드는 가장 좋은 방법입니다.

"US|New York|D.M.Street" 
    "US|New York|ShoppingMall" 
    "INDIA|Dehli|G.M. Road" 
    "INDIA|Mumbai|Harbour Street" 
    "US|Washington|WhiteHouse" 
    "INDIA|Dehli|Rajpath" 
    "INDIA|Mumbai|CST" 

이 컬렉션의 트리보기를 C#으로 채 웁니다. 다음과 같은 방식으로

Country 
| 
US => NewYork ==========>D.M.Street 
|  |  ==========>ShoppingMall 
     | 
|  Washinton==========>WhiteHouse 
| 
INDIA=>Dehli ==========>G.M. Road 
     |   ==========>Rajpath 
     | 
     Mumbai ==========>CST 
       ==========>Harbour Street 

어떻게 준비 할 수 있습니까? 유대인 수집 또는 다른 방법? 여기

+1

"Newyork"과 "New York"이 실제로 찾고있는 솔루션의 한 노드에 일치합니까? – Jay

+0

opps..spell correct –

답변

1

내가이 접근 할 방법은 다음과 같습니다

요소의 중첩 된 계층 구조를 (자세한 내용이 필요한 경우이 나중에 확장 할 수 있습니다) 개최 클래스와 컬렉션을 만듭니다.

 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); 
      } 
     } 

    } 
+0

나를 위해 완벽하게 작동합니다. 나는 이것을 telerik 컨트롤과 함께 사용한다. –

1

에 항목을 추가하는 데 사용, 당신은 워싱턴 가정 이것이 내가 샘플에서 수정 한 샘플 데이터에 "뉴욕"과 "뭄바이"의 일치 철자를 고려하지 않는

var nodes = GetData().Select(data => data.Split('|')).GroupBy(x => x[0]).Select(
    country => new TreeNode(country.Key, country.GroupBy(x => x[1]).Select(
     city => new TreeNode(city.Key, city.Select(
     place => new TreeNode(place[2])) 
     .ToArray())) 
     .ToArray())) 
    .ToArray(); 

    treeView1.Nodes.AddRange(nodes); 

enter image description here

참고 : LINQ의 혼란을 NT .

+0

Jay에게 감사드립니다. 도움이됩니다. Telerik 트리 뷰 컨트롤에서 같은 것에 대해 생각 해보시겠습니까? –

+0

@RedSwan Telerik 컨트롤의 세부 사항을 알지 못하지만 노드에 같은 유형의 생성자가있는 경우 동일한 패턴을 따를 수 있습니다 :'ctor (문자열 텍스트, <일부 노드 노드 컬렉션>) 및 if 자식 노드의 콜렉션은 배열 일 필요는 없으며'.ToArray()'호출을 생략 할 수 있습니다. – Jay