Walking a hierarchy table with Linq

后端 未结 3 1682
离开以前
离开以前 2021-01-14 06:10

I have a table with two columns, GroupId and ParentId (both are GUIDS). The table forms a hierarchy so I can look for a value in the “GroupId” filed, when I have found it I

3条回答
  •  抹茶落季
    2021-01-14 06:34

    LINQ is not designed to handle recursive selection.

    It is certainly possible to write your own extension method to compensate for that in LINQ to Objects, but I've found that LINQ to Entities does not like functionality not easily translated into SQL.

    Edit: Funnily enough, LINQ to Entities does not complain about Matt Warren's take on recursion using LINQ here. You could do:

    var result = db.Table.Where(item => item.GroupId == 5)
                         .Traverse(item => db.Table.Where(parent 
                                                           => item.ParentId == parent.GroupId));
    

    using the extension method defined here:

    static class LinqExtensions
    {
        public static IEnumerable Traverse(this IEnumerable source,
                                                 Func> selector){
        foreach(T item in source){
            yield return item;
            IEnumerable children = selector(item);
            foreach (T child in children.Traverse(selector))
            {
                yield return child;
            }
        }
    }
    

    Performace might be poor, though.

提交回复
热议问题