将项目分组到父级 - >孩子 - >大孩子的关系

时间:2011-07-14 21:34:49

标签: c# .net linq c#-3.0

我的课程如下:

public class Item
    {
        public int ItemID { get; set; }
        public int GroupLevel { get; set; }
        public string ItemName { get; set; }
        public string ItemDesc { get; set; }
    }

这会返回一个展平的IEnumerable结果,但我需要将它们分组为父 - >孩子 - >大子关系,基于GroupLevel和ItemID。以下是当前数据的外观:

ItemID:     1
GroupLevel: 1
ItemName:   All Groups
ItemDesc:   Item 1 description
ParentID:   null

ItemID:     2
GroupLevel: 2
ItemName:   Boulder
ItemDesc:   Boulder description
ParentID:   1

ItemID:     3
GroupLevel: 2
ItemName:   Atlanta
ItemDesc:   Atlanta description
ParentID:   1

ItemID:     4
GroupLevel: 3
ItemName:   Boulder - Boulder south
ItemDesc:   Grand-child of Boulder (ID: 2)
ParentID:   2

ItemID:     5
GroupLevel: 3
ItemName:   Boulder - Boulder North
ItemDesc:   Another grand-child of Boulder (ID: 2)
ParentID:   2

ItemID:     6
GroupLevel: 3
ItemName:   Atlanta - West
ItemDesc:   Grand-child of Atlanta (ID: 3)
ParentID:   3

我希望数据的结构如下:

ItemID:     1
GroupLevel: 1
ItemName:   All Groups
ItemDesc:   Item 1 description
ParentID:       null

    ItemID:     2
    GroupLevel: 2
    ItemName:   Boulder
    ItemDesc:   Boulder description
    ParentID:       1

        ItemID:     4
        GroupLevel: 3
        ItemName:   Boulder - Boulder south
        ItemDesc:   Grand-child of Boulder (ID: 2)
        ParentID:       2

        ItemID:     5
        GroupLevel: 3
        ItemName:   Boulder - Boulder North
        ItemDesc:   Another grand-child of Boulder (ID: 2)
        ParentID:       2


    ItemID:     3
    GroupLevel: 2
    ItemName:   Atlanta
    ItemDesc:   Atlanta description
    ParentID:       1

        ItemID:     6
        GroupLevel: 3
        ItemName:   Atlanta - West
        ItemDesc:   Grand-child of Atlanta (ID: 3)
        ParentID:       3

有什么建议吗?谢谢。

2 个答案:

答案 0 :(得分:1)

你的意思是这样的:

    List<Item> itemlist;
    List<Item> newItemList;

    public void main()
    {
        //Find all root items (aka, no parents)
        foreach (Item item in itemlist)
        {
            if (item.Parent == null) getObjects(item.ID, 0);
        }
    }

    public void getObjects(Item me, int deep)
    {
        //Store node
        Console.WriteLine("this is me: " + me.ID);
        Console.WriteLine("I am this many levels deep: " + deep);
        newItemList.Insert(me);

        //Find my children
        foreach (Item item in itemlist)
        {
            if (item.Parent == me.ID) getObjects(item.ID, (deep + 1));
        }
    }

答案 1 :(得分:0)

我认为这对你有用

linq-groupbymany-dynamically

您可以阅读示例,并创建父级 - &gt;孩子 - &gt;你喜欢的大孩子关系树......