将项目分组为Parent ->孩子比;个孙子的关系
本文关键字:关系 孩子 项目 Parent | 更新日期: 2023-09-27 18:02:03
我的class如下:
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将它们分组为Parent -> Child ->孙子关系。下面是当前数据的样子:
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
任何建议吗?谢谢你。
你的意思是:
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));
}
}
我认为这对你很有用
linq-groupbymany-dynamically
您可以阅读示例,并根据需要创建Parent -> Child ->孙子-子关系树.....