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

发布于 2024-12-20 21:31:44 字数 654 浏览 0 评论 0原文

我正在尝试从以下字符串准备树视图控件。

    "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

如何准备这个?使用集合还是其他方式?

I am trying to prepare the tree view control from folowing strings.

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

I want to populate the tree view from this collection in C#. in following manner

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

how i can prepare this ? usning collection or else way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤独陪着我 2024-12-27 21:31:44

我的处理方法如下:

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

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

    }

Here's how I would approach this:

Create a class and a collection to hold a nested hierarchy of elements (this can be expanded later if more detail is needed).

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

}

Then parse your data into the collection (note that this will support any level of nesting in your record structure without a need to modify the code):

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

and this is the recursive method used to add the items to the tree

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

    }
ζ澈沫 2024-12-27 21:31:44

给定一个 GetData() 函数,该函数返回包含所有字符串数据的 IEnumerable,并假设您需要一堆 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);

在此处输入图像描述

请注意,这并不能解释我所拥有的示例数据中“New York”和“Mumbai”的拼写不一致的情况在示例中已更正。

Given a GetData() function that returns IEnumerable<string> with all of the string data, and assuming you want a jumble of 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);

enter image description here

Note that this does not account for the inconsistent spellings of "New York" and "Mumbai" in your sample data, which I have corrected in the sample.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文