我在这个结构中有一个表
ListA labelName
1 Colorado
1 Wyoming
1 Illinois
2 New York
2 Ohio
我正在尝试创建一棵树,其中如果 LISTA = 1,它会位于一个名为“header one”的节点下,而科罗拉多州、怀俄明州、伊利诺伊州则作为它的叶子,并且值“2”......通过这样做,我得到了 3“标题一”节点,而不是将所有这三个节点都放在一个...
SqlCommand cmd = con.CreateCommand();
comd.CommandText = "SELECT * FROM myTable";
con.Open();
SqlDataReader reader = comd.ExecuteReader();
while (reader.Read())
{
City MyData = new City();
MyData.ListA = reader["ListA"].ToString().Trim();
MyData.labelName = reader["labelName"].ToString().Trim();
giveData.Add(MyData);
}
int count = 1;
List<TreeNode> myNode = new List<TreeNode>();
foreach (City MyData in giveData)
{
// 1st foreach
if (MyData.ListA != "1")
{
TreeNode treeNode = new TreeNode();
treeNode.id = count++;
treeNode.name = "Header One";
treeNode.leaf = false;
List<TreeNode> Level1 = new List<TreeNode>();
foreach (City labelName in giveData)
{
if (labelName.ListA == "1")
{// 2nd foreach
TreeNode node1 = new TreeNode();
node1.id = count++;
node1.name = labelName.labelName;
node1.leaf = true;
Level1.Add(node1);
}
}
treeNode.children = Level1;
myNode.Add(treeNode);
}
else if (MyData.ListA != "2")
{
TreeNode treeNode = new TreeNode();
treeNode.id = count++;
treeNode.name = "Header Two";
treeNode.leaf = false;
List<TreeNode> Level1 = new List<TreeNode>();
foreach (City labelName in giveData)
{
if (labelName.ListA == "2")
{// 2nd foreach
TreeNode node1 = new TreeNode();
node1.id = count++;
node1.name = labelName.labelName;
node1.leaf = true;
Level1.Add(node1);
}
}
treeNode.children = Level1;
myNode.Add(treeNode);
}
}
return JsonConvert.SerializeObject(myNode);
处理此问题的最佳方法是什么