C# | .NET 4.5 | 实体框架 5
我在实体框架中有一个类,如下所示:
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 编写了递归,将其放入 SP,然后将其拉入 Entity。对我来说似乎比使用 Linq 更干净、更容易,从评论来看,Linq 和 Entity 似乎不是最好的选择。感谢所有的帮助!