将所有子级放入一个列表 - 递归 C# [英] Get All Children to One List - Recursive C#

查看:15
本文介绍了将所有子级放入一个列表 - 递归 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

C# | .NET 4.5 | Entity Framework 5

我在实体框架中有一个类,如下所示:

I have a class in Entity Framework that looks like this:

public class Location
{
   public long ID {get;set;}
   public long ParentID {get;set;}
   public List<Location> Children {get;set;}
}

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

ID is the identifier of the location, ParentID links it to a parent, and Children contains all of the children locations of the parent location. I'm looking for some easy way, likely recursively, to get all "Location" and their children to one single List containing the Location.ID's. I'm having trouble conceptualizing this recursively. Any help is appreciated.

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

This is what I have so far, its an extension to the entity class, but I believe it could be done better/simpler:

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,然后将其拉入实体.对我来说似乎比使用 Linq 更干净、更容易,从评论来看,Linq 和 Entity 似乎不是最好的路线.感谢大家的帮助!

I ended up writing the recursion in SQL, throwing that in a SP, and then pulling that into Entity. Seemed cleaner and easier to me than using Linq, and judging by the comments Linq and Entity don't seem the best route to go. Thanks for all of the help!

推荐答案

你可以做 多选

List<Location> result = myLocationList.SelectMany(x => x.Children).ToList();

您可以将 where 条件用于某些选择性结果,例如

You can use where condition for some selective results like

List<Location> result = myLocationList.Where(y => y.ParentID == someValue)
                                      .SelectMany(x => x.Children).ToList();

如果您只需要孩子的 ID,您可以这样做

If you only required Id's of Children you can do

List<long> idResult = myLocationList.SelectMany(x => x.Children)
                                    .SelectMany(x => x.ID).ToList();

这篇关于将所有子级放入一个列表 - 递归 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆