Model:
public class PerSon
{
[DisplayName("标识id")]
public string id { get; set; }
[DisplayName("名称")]
public string name { get; set; }
[DisplayName("年龄")]
public int age { get; set; }
[DisplayName("父级")]
public int? PerSonId { get; set; }
/// <summary>
/// 该分类的子分类
/// </summary>
public List<PerSon> items { get; set; }
}
Code:
class Program
{
static List<PerSon> list = new List<PerSon>()
{
new PerSon(){ id = "", age=, name="张飞1", PerSonId = null },
new PerSon(){ id = "", age=, name="张飞7", PerSonId = null },
new PerSon(){ id = "", age=, name="张飞8", PerSonId = null },
new PerSon(){ id = "", age=, name="张飞5", PerSonId = },
new PerSon(){ id = "", age=, name="张飞4", PerSonId = },
new PerSon(){ id = "", age=, name="张飞3", PerSonId = },
new PerSon(){ id = "", age=, name="张1", PerSonId = },
new PerSon(){ id = "", age=, name="张2", PerSonId = },
new PerSon(){ id = "", age=, name="张飞1", PerSonId = },
};
static void Main(string[] args)
{
var ViewData = new List<PerSon>();
list.ForEach((u) =>
{
if (u.PerSonId == null)
{
ViewData.Add(new PerSon()
{
age = u.age,
id = u.id,
name = u.name,
items = getitem(u.id)
});
}
});
var a = ViewData;
}
public static List<PerSon> getitem(string id)
{
List<PerSon> perSons = new List<PerSon>();
foreach (var items in list)
{
if (items.PerSonId.ToString() == id)
{
perSons.Add(new PerSon()
{
age = items.age,
id = items.id,
name = items.name,
PerSonId = Convert.ToInt32(id),
items = getitem(items.id)
});
}
}
return perSons;
}
}