繁体   English   中英

这是使用字符串集合构建树视图控件的最佳方法

[英]which is the best way to build the tree view control using string collection

我试图从下面的字符串准备树视图控件。

    "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

我怎么准备这个? 用户收集还是其他方式?

这是我如何处理这个问题:

创建一个类和一个集合来保存元素的嵌套层次结构(如果需要更多细节,可以在以后扩展)。

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>
{

}

然后将数据解析到集合中(请注意,这将支持记录结构中的任何级别的嵌套,而无需修改代码):

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

这是用于将项添加到树的递归方法

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

    }

给定一个GetData()函数,该函数返回包含所有字符串数据的IEnumerable<string> ,并假设您想要混杂的LINQ:

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

在此输入图像描述

请注意,这并未考虑样本数据中“纽约”和“孟买”的拼写不一致,我已在样本中对其进行了更正。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM