我怎么能转换与PARENTID项目清单成大树? [英] How can I convert a list of items with ParentID into a tree?
问题描述
我使用的是SQL Server和实体框架。在我的数据库,我有以下数据:
I'm using SQL Server and Entity Framework. On my database I have the following data:
ID | Name | ParentID
1 | Fire | null
2 | Fire2 | 1
3 | Fire3 | 2
4 | Blast | 2
5 | Water | null
6 | Water2 | 5
7 | WaterX | 5
我不会有大量的数据,所以一旦检索了从数据库是完全可以接受的。
I won't have massive data, so retrieving everything at once from the database is perfectly acceptable.
我想检索该数据并显示在屏幕上为树。
I want to retrieve this data and display on screen as a "tree".
Fire
Fire2
Fire3 Blast
Water
Water2 WaterX
我应该怎么做呢?我是否应该建立某种形式的递归来呈现呢?我应该以某种方式列表转换为IGrouping?
How should I do this? Should I create some sort of recursion to render it? Should I somehow convert the list to an IGrouping?
我在遇到麻烦的平面列表转换成的东西,我可以分层呈现在屏幕上,我怎么能这样做呢?
I'm having trouble converting the flat list into something that I can render hierarchically on the screen, how could I do that?
推荐答案
如果你可以另一个属性添加到您的类,它有子项是这样的:
If you can add another property to your class that has the child items like this:
public class Thing
{
public Thing()
{
Things = new List<Thing>();
}
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public List<Thing> Things { get; set; }
}
然后,你可以轻松地集团的项目给他们的父母是这样的:
Then you can easily group the items to their parents like this:
var things = new List<Thing>
{
new Thing { Id = 1, Name = "Fire", ParentId = null },
new Thing { Id = 2, Name = "Fire2", ParentId = 1 },
new Thing { Id = 3, Name = "Fire3", ParentId = 2 },
new Thing { Id = 4, Name = "Blast", ParentId = 2},
new Thing { Id = 5, Name = "Water", ParentId = null },
new Thing { Id = 6, Name = "Water2", ParentId = 5 },
new Thing { Id = 7, Name = "Waterx", ParentId = 6 }
};
var groupedThings = new List<Thing>();
foreach (var thing in things)
{
if (thing.ParentId != null)
{
things.First(t => t.Id == thing.ParentId).Things.Add(thing);
}
else
{
groupedThings.Add(thing);
}
}
groupedThings.Dump();
这篇关于我怎么能转换与PARENTID项目清单成大树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!