相关疑难解决方法(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万
查看次数

如何确定对象的类型是否实现IEnumerable <X>,其中X使用Reflection从Base派生

给一个基类Base,我想写一个方法Test,像这样:

private static bool Test(IEnumerable enumerable)
{
...
}
Run Code Online (Sandbox Code Playgroud)

这样的测试如果O类型实现的任何接口返回true IEnumerable<X>,其中X从派生Base,所以,如果我这样做:

public static IEnumerable<string> Convert(IEnumerable enumerable)
{
    if (Test(enumerable))
    {
        return enumerable.Cast<Base>().Select(b => b.SomePropertyThatIsString);
    }

    return enumerable.Cast<object>().Select(o => o.ToString());
}
Run Code Online (Sandbox Code Playgroud)

......使用Reflection,它会做正确的事情.我确信这是跨越所有类型接口的问题,找到符合要求的第一个,但我很难找到IEnumerable<>它们之间的通用.

当然,我可以考虑一下:

public static IEnumerable<string> Convert(IEnumerable enumerable)
{
    return enumerable.Cast<object>().Select(o => o is Base ? ((Base)o).SomePropertyThatIsString : o.ToString());
}
Run Code Online (Sandbox Code Playgroud)

......但是把它想象成一个思想实验.

c# linq reflection

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

linq ×2

entity-framework ×1

recursion ×1

reflection ×1