相关疑难解决方法(0)

让所有孩子到一个列表 - 递归C#

C#| .NET 4.5 | 实体框架5

我在Entity Framework中有一个类如下所示:

public class Location
{
   public long ID {get;set;}
   public long ParentID {get;set;}
   public List<Location> Children {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

ID是位置的标识符,ParentID将其链接到父级,Children包含父级位置的所有子级位置.我正在寻找一些简单的方法,可能递归地将所有"Location"和他们的孩子放到一个包含Location.ID的List中.我在递归地概念化这个问题时遇到了麻烦.任何帮助表示赞赏.

这是我到目前为止,它是实体类的扩展,但我相信它可以做得更好/更简单:

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();
}
Run Code Online (Sandbox Code Playgroud)

更新

我最终在SQL中编写了递归,将其抛入SP,然后将其拉入实体.看起来更干净,比使用Linq更容易,并且根据评论判断Linq和Entity似乎不是最好的路线.感谢您的帮助!

c# linq recursion entity-framework

15
推荐指数
7
解决办法
4万
查看次数

标签 统计

c# ×1

entity-framework ×1

linq ×1

recursion ×1