2015-07-12 79 views
1

我正在使用SQL Server和实体框架。在我的数据库,我有以下数据:如何将带有ParentID的项目列表转换为树形?

ID | Name | ParentID 
1 | Fire | null 
2 | Fire2 | 1 
3 | Fire3 | 2 
4 | Blast | 2 
5 | Water | null 
6 | Water2 | 5 
7 | WaterX | 5 

我不会有大量的数据,所以在一次从数据库是完全可以接受的检索一切。

我想检索这些数据并在屏幕上显示为“树”。

Fire 
    Fire2 
Fire3 Blast 

    Water 
Water2 WaterX 

我该怎么做?我应该创建某种递归来呈现它吗?我应该不知何故将列表转换为IGrouping?

我无法将平板列表转换为可以在屏幕上分层显示的东西,我该怎么做?

+0

递归是答案 –

+0

这就像5个不同的问题...你想知道如何将其转换为结构树对象?或者你想知道如何从后端获取这个列表并在前端渲染为一棵树?为此,我会说找到一个你喜欢的图书馆并格式化该图书馆的数据。 – thinklarge

+0

对不起,我只是在寻找一种方法来实现以树形格式显示数据的最终结果。我不知道哪个是最好的方法,所以我在同一时间想着5个不同的东西,这让我很头疼哈哈:) – BrunoLM

回答

1

如果你可以添加另一个属性类具有子项是这样的:

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; } 
} 

然后你就可以轻松地集团的项目,以他们的父母是这样的:

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(); 

1

这是我知道的最简单的方法:

var things = new [] 
{ 
    new { Id = 1, Name = "Fire", ParentId = (int?)null }, 
    new { Id = 2, Name = "Fire2", ParentId = (int?)1 }, 
    new { Id = 3, Name = "Fire3", ParentId = (int?)2 }, 
    new { Id = 4, Name = "Blast", ParentId = (int?)2 }, 
    new { Id = 5, Name = "Water", ParentId = (int?)null }, 
    new { Id = 6, Name = "Water2", ParentId = (int?)5 }, 
    new { Id = 7, Name = "Waterx", ParentId = (int?)5 } 
}; 

var tree = things.ToLookup(x => x.ParentId, x => new { x.Id, x.Name }); 

的树是这个样子:

tree

这应该是相当容易的,现在来呈现。