让所有的孩子一个列表 - 递归C# [英] Get All Children to One List - Recursive C#

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

问题描述

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

C# | .NET 4.5 | Entity Framework 5

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

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将其链接到父级,并且儿童包含父位置的所有子项位置。我正在寻找一些简单的方法,可能递归地将所有位置和他们的孩子列入包含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();
}

UPDATED

我最终在SQL中编写递归,将其抛在SP中,然后将其拉入Entity。看起来比使用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!

推荐答案

您可以执行 SelectMany

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

您可以使用某些选择性结果的条件,如

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天全站免登陆