走LINQ的层次结构表 [英] Walking a hierarchy table with Linq

查看:86
本文介绍了走LINQ的层次结构表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两列,groupId和的ParentId(均为GUID)的表。该表形成了一个层次,所以我可以找提起在的GroupId的值,当我发现它,我可以看一下它的ParentId。这的ParentId也会出现在不同记录的GroupId。我可以用它来从任何一点到根(根是一个空GUID)步行层次树。我想要做的就是一个记录列表,当我知道一个GroupId的。这将与groupId和所有的父母回到根记录该记录。这可能与LINQ的,如果是这样,任何人都可以提供的代码片段?

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 can look at its ParentId. This ParentId will also appear in the GroupId of a different record. I can use this to walk up the hierarchy tree from any point to the root (root is an empty GUID). What I’d like to do is get a list of records when I know a GroupId. This would be the record with the GroupId and all the parents back to the root record. Is this possible with Linq and if so, can anyone provide a code snippet?

推荐答案

LINQ是不是设计来处理递归的选择。

LINQ is not designed to handle recursive selection.

当然可以编写自己的扩展方法,为在LINQ到补偿对象,但我发现,LINQ到实体不喜欢的功能不容易翻译。到SQL

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.

编辑:
有趣的是,LINQ到实体不抱怨使用LINQ <马特·沃伦我们来递归一HREF =htt​​p://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/fe3d441d-1e49-4855-8ae8-60068b3ef741相对=nofollow>此处。你可以这样做:

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.

这篇关于走LINQ的层次结构表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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