Walking a hierarchy table with Linq

后端 未结 3 1683
离开以前
离开以前 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:32

    It's definitely possible with Linq, but you'd have to make a DB call for each level in the heirarchy. Not exactly optimal.

    0 讨论(0)
  • 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<T> Traverse<T>(this IEnumerable<T> source,
                                                 Func<T,IEnumerable<T>> selector){
        foreach(T item in source){
            yield return item;
            IEnumerable<T> children = selector(item);
            foreach (T child in children.Traverse(selector))
            {
                yield return child;
            }
        }
    }
    

    Performace might be poor, though.

    0 讨论(0)
  • 2021-01-14 06:40

    The other respondents are right - performance is going to be pretty bad on this, since you'll have to make multiple round-trips. This will be somewhat dependent on your particular case, however - is your tree deep and will be people be performing this operation often, for instance.

    You may be well served by creating a stored procedure that does this (using a CTE), and wiring it up in the Entities Designer to return your particularly defined Entity.

    0 讨论(0)
提交回复
热议问题