如何将带有ParentID的项目列表转换为树?

时间:2015-07-12 01:50:40

标签: c# asp.net-mvc linq entity-framework

我正在使用SQL Server和Entity Framework。在我的数据库中,我有以下数据:

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吗?

我无法将平面列表转换为可以在屏幕上分层渲染的内容,我该怎么做?

2 个答案:

答案 0 :(得分: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 :(得分: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

现在应该很容易呈现。