1

我有一个包含这些数据的表

State       Cities

 TX         Houston
 TX         San Antonio
 TX         Austin
 TX         Austin
 PA         Philadelphia
 PA         Pitssburgh
 PA         Pittsburgh
 PA         
 CO         Boulder
 CO         Denver

我正在尝试实现一棵树,它将这三个状态作为节点,将各自的城市作为叶子。

在 c# 上,我正在创建一个列表。

            comd.CommandText = "SELECT * FROM MyTable";

            con.Open();
            SqlDataReader reader = comd.ExecuteReader();
            while (reader.Read())
            {
                City myData = new City();
                myData.State = reader["State"].ToString().Trim();
                myData.Cities = reader["Cities"].ToString().Trim();
                giveData.Add(myData);
            }  
            int count = 1;
            List<TreeNode> myNode = new List<TreeNode>();
            foreach (City myData in giveData)
            {
                TreeNode treeNode = new TreeNode();
                treeNode.id = count++;
                treeNode.name = myData.State;
                treeNode.leaf = false;

                List<TreeNode> Level1 = new List<TreeNode>();
                if (mydata.Cities != null)
                {
                    if (mydata.Cities!= "")
                    {
                        foreach (City State in result)
                        {
                            TreeNode node1 = new TreeNode();
                            node1.id = count++;
                            node1.name = myData.Cities;
                            node1.leaf = true;

                            Level1.Add(node1);
                         }
                     }
                }
                treeNode.children = Level1;
                myNode.Add(treeNode);
            }

            return JsonConvert.SerializeObject(myNode);

我得到的是所有 4 个 TX 和 PA 和 2 个 CO 作为树节点,在 TX 节点下我得到两个奥斯汀......

如何实施我的列表,以便我只得到一个 TX、一个 PA 和一个 CO,如果有两个城市,我只有一个城市......

4

1 回答 1

1

我无法测试它,但应该这样做:

comd.CommandText = "SELECT * FROM MyTable";

con.Open();
SqlDataReader reader = comd.ExecuteReader();
while (reader.Read())
{
    City myData = new City();
    myData.State = reader["State"].ToString().Trim();
    myData.Cities = reader["Cities"].ToString().Trim();
    giveData.Add(myData);
}  
int count = 1;
Dictionary<string, TreeNode> result = new Dictionary<string, TreeNode>();
foreach (City myData in giveData) 
{
    if (result.ContainsKey(myData.State ))
    {
        result[myData.State].children.Add(new TreeNode() {
            id = count++,
            name = myData.Cities,
            leaf = true
        });
    }
    else
    {
        result.add(giveData.State, new TreeNode() {
            id = count++,
            name = myData.State,
            leaf = false,
            children = new List<TreeNode>()
        });
    }
}

return JsonConvert.SerializeObject(result.Values);
于 2012-12-21T21:09:07.460 回答