C#列出TreeView的组和子组

时间:2018-08-11 16:34:04

标签: c# .net winforms linq treeview

我有一个自定义项目:

List<Class_Items_Data> All_Items_List = new List<Class_Items_Data>();

public class Class_Items_Data
{
public string item_category { get; set; }
public string item_sub_category { get; set; }
public string item_name { get; set; }
}

例如:

item_category = "Food"    , item_sub_category = "Main Dish" , item_name = "A" };
item_category = "Beverage", item_sub_category = "Hot Drink" , item_name = "B" };
item_category = "Food"    , item_sub_category = "Soup"      , item_name = "C" };
item_category = "Beverage", item_sub_category = "Cold Drink", item_name = "D" }

我想将它们放在Treeview中,以便向我显示以下结果:

enter image description here

编辑#

我正在使用Winform

到目前为止,我已经尝试过此操作(显示正确值的消息框)

  var ItemsGroups = All_Items_List 
    .GroupBy(x => new { Group = x.item_category_group, Category = x.item_category})
    .GroupBy(x => new { Group = x.Key.Group }).OrderBy(x => x.Key.Group);

            foreach (var Group in ItemsGroups)
            {
                MessageBox.Show("Group : " + Group.Key.Group);
                foreach (var Category in Group)
                {
                    MessageBox.Show("SubCategory : " + Category.Key.Category);
                    foreach (var Item in Category)
                    {
                        MessageBox.Show("Item : " + Item.item_name_original);
                    }
                }
            }

1 个答案:

答案 0 :(得分:1)

将循环更改为

foreach (var Group in ItemsGroups) {
    TreeNode groupNode = treeView1.Nodes.Add(Group.Key.Group);
    foreach (var Category in Group) {
        TreeNode categoryNode = groupNode.Nodes.Add(Category.Key.Category);
        foreach (var Item in Category) {
            categoryNode.Nodes.Add(Item.item_name_original);
        }
    }
}