项目中所使用:使用EF可以将父子项全部加载进来,所以只是用递归将父子项放入list,反射加泛型使其通用。
一,实体:
public class Sys_city
{
public Sys_city()
{
children = new List<Sys_city>();
}
public int Id { get; set; }
[StringLength(100)]
public string title { get; set; }
[StringLength(20)]
public string zip_Code { get; set; }
public int? ParentId { get; set; }
public int level { get; set; }
public int sort { get; set; }
[StringLength(300)]
public string CityFullName { get; set; }
public string parent_s { get; set; }
public virtual Sys_city Sys_City { get; set; }
[ForeignKey("ParentId")]
public virtual ICollection<Sys_city> children { get; set; }
}
二,数据表:
三,泛型实现:
public class Recursion
{
public IEnumerable<T> GetChildren<T>(ICollection<T> children, string propertyName)
{
if (children.Count() > 0)
{
return children.Concat(children.SelectMany(t => GetChildren(t.GetType().GetProperty(propertyName).GetValue(t) as ICollection<T>, propertyName)));
}
else
{
return children.ToList();
}
}
public T GetFather<T>(T single, string propertyName, ref List<T> list) where T : class
{
if (single.GetType().GetProperty(propertyName).GetValue(single) != null)
{
list.Add(GetFather(single.GetType().GetProperty(propertyName).GetValue(single) as T, propertyName, ref list));
return single;
}
else
{
return single;
}
}
四,使用方法:
var single = 这里根据ID查询出单条记录
Recursion rn = new Recursion();
//这步操作取出所有子项,但不包含自身
var children = rn.GetChildren(single.children, "children").ToList();
//这步将自身加入
children.Insert(0, single);
List<Sys_city> Ecity = new List<Sys_city>();
//这步操作取出所有父项,但不包含自身
var e = rn.GetFather(single, "Sys_City", ref Ecity);
//这步将自身加入
Ecity.Add(e);