C# | .NET 4.5 | Entity Framework 5
我有一个在Entity Framework中的类,长这样:
public class Location
{
public long ID {get;set;}
public long ParentID {get;set;}
public List<Location> Children {get;set;}
}
ID是位置的标识符,ParentID将其链接到父级,而Children包含父级位置的所有子级位置。我正在寻找一种简单的方法(可能是递归方式),将所有“位置”及其子代放入一个包含Location.ID的单个列表中。我在递归方面遇到了困难。希望有所帮助。
这是我到目前为止所做的,它是实体类的一个扩展,但我认为可以做得更好/更简单:
public List<Location> GetAllDescendants()
{
List<Location> returnList = new List<Location>();
List<Location> result = new List<Location>();
result.AddRange(GetAllDescendants(this, returnList));
return result;
}
public List<Location> GetAllDescendants(Location oID, ICollection<Location> list)
{
list.Add(oID);
foreach (Location o in oID.Children)
{
if (o.ID != oID.ID)
GetAllDescendants(o, list);
}
return list.ToList();
}
更新
最终我用 SQL 写了递归函数,将其放在存储过程中,然后将其导入到 Entity 中。相较于使用 Linq,这种方法看起来更加清晰和容易,而且根据评论来看,Linq 和 Entity 似乎不是最佳选择。感谢所有的帮助!