C#形成嵌套父对象

时间:2017-02-07 14:49:02

标签: c# linq

我有一个类似下面的类结构,

class Employees
{
public string Id {get;set;}
public string BossId {get;set;}
public List<Employees> Subordinates {get;set;}
}

目前我有一张包含4条记录的清单。

1. Id = 1, BossId = null
2. Id = 2, BossId = 1
3. Id = 3, BossId = 2
4. Id = 4, BossId = null

现在我需要通过填充Subordinates属性来形成如下所示的List对象。

Employees 
{
Id: 1
Subordinates : 
 { 
   Employees :
   {
     Id : 2
     Subordinates :
     {
       Employees:
       {
         Id: 3
         Subordinates : null
       }
     }
   }
 }
},
Id: 2
Subordinates: null
}

请帮忙

1 个答案:

答案 0 :(得分:2)

为了让Employees更容易找到Id,我建议您先创建一个字典:

var employeesById = employees.ToDictionary(emp => emp.Id, emp => emp);

然后,您可以遍历列表并适当填写Subordinates列表:

foreach(var employee in employees)
{
    if (employee.BossId == null) continue;

    // get boss by BossId
    Employees boss = employeesById[employee.BossId];

    // make sure Subordinates is initialised
    if (boss.Subordinates == null) boss.Subordinates = new List<Employees>();

    // add subordinate
    boss.Subordinates.Add(employee);
}