如何从C#中的列表创建嵌套列表?

时间:2018-09-27 09:57:47

标签: c# list object type-conversion

我有以下方法可以返回C#中的项目列表。

public List<LevelItem> GetItemList()
    {
        List<LevelItem> items = new List<LevelItem>
        {
            new LevelItem(){ ItemID = 70, Name="Home", ChildCount = 1, Level = 0, ParentID = 0 },
            new LevelItem(){ ItemID = 71, Name="Pages", ChildCount = 1, Level = 0, ParentID = 0 },
            new LevelItem(){ ItemID = 72, Name="Pages II", ChildCount = 1, Level = 0, ParentID = 0 },
            new LevelItem(){ ItemID = 77, Name="My World", ChildCount = 1, Level = -1, ParentID = 0 },
            new LevelItem(){ ItemID = 79, Name="Level 3", ChildCount = 0, Level = 0, ParentID =  0},
            new LevelItem(){ ItemID = 73, Name="Page III", ChildCount = 0, Level = 0, ParentID = 71},
            new LevelItem(){ ItemID = 74, Name="Page IV", ChildCount = 0, Level = 0, ParentID = 70 },
            new LevelItem(){ ItemID = 75, Name="Level 1", ChildCount = 1, Level = 0, ParentID = 72 },
            new LevelItem(){ ItemID = 76, Name="Hello 1", ChildCount = 1, Level = 0, ParentID = 77 },
            new LevelItem(){ ItemID = 78, Name="Level 2", ChildCount = 0, Level = -1, ParentID = 76 }
        };
        return items;
    }

还有一个具有以下属性的类。

public class LevelItem
    {
        public int ItemID { get; set; }
        public string Name { get; set; }
        public int ChildCount { get; set; }
        public int ParentID { get; set; }
        public int Level { get; set; }
        public  List<LevelItem> ItemList;
    }

基本上我想根据它们的ParentIDItemID属性将上述列表转换为嵌套列表。我想得到类似这样的结果:

{ 
    ItemID = 70, 
    Name="Home", 
    ChildCount = 1, 
    Level = 0, 
    ParentID = 0,
    { 
        ItemID = 74, 
        Name="Page IV", 
        ChildCount = 0, 
        Level = 0, 
        ParentID = 70 
    }     
}
{ 
    ItemID = 71, 
    Name="Pages", 
    ChildCount = 1, 
    Level = 0, 
    ParentID = 0, 
    { 
        ItemID = 73, 
        Name="Page III", 
        ChildCount = 0, 
        Level = 0, 
        ParentID = 71
    } 
}
{ 
    ItemID = 72, 
    Name="Pages II", 
    ChildCount = 1, 
    Level = 0, 
    ParentID = 0 
    { 
        ItemID = 75, 
        Name="Level 1", 
        ChildCount = 1, 
        Level = 0, 
        ParentID = 72 
    }
}
{ 
    ItemID = 77, 
    Name="My World", 
    ChildCount = 1, 
    Level = -1, 
    ParentID = 0,
    {   
        ItemID = 76, 
        Name="Hello 1", 
        ChildCount = 1, 
        Level = 0, 
        ParentID = 77 , 
        { 
            ItemID = 78, 
            Name="Level 2", 
            ChildCount = 0, 
            Level = -1, 
            ParentID = 76 
        }
    }
}
{ 
    ItemID = 79, 
    Name="Level 3", 
    ChildCount = 0, 
    Level = 0, 
    ParentID =  0
}

有可能吗?

0 个答案:

没有答案