递归林格集团 [英] Recursive Linq Grouping

查看:99
本文介绍了递归林格集团的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方案:
我有数据库表存储另一个表的多对多关系的层次结构。一个项目可以有多个孩子,也可以有多个父母。

Scenario: I have database table that stores the hierarchy of another table's many-to-many relationship. An item can have multiple children and can also have more than one parent.

Items    
------ 
ItemID (key)

Hierarchy
---------
MemberID (key)
ParentItemID (fk)
ChildItemID (fk)

样本层次结构:

Level1  Level2  Level3
X       A       A1
                A2
        B       B1
                X1
Y       C

我想将所有小孩节点分组,每个 / strong>节点。

I would like to group all of the child nodes by each parent node in the hierarchy.

Parent  Child
X       A1
        A2
        B1
        X1
A       A1
        A2
B       B1
        X1
Y       C

注意在Parent列中没有叶节点,以及Child列如何仅包含叶子节点。 >

  • 理想情况下,我想要t他的结果是以 IEnumerable <\\ c $ c> IGrouping 项目,项目>> 的形式,其中的关键是父母,组的项目都是儿童

  • 理想情况下,我想要一个实体提供商可以转换为T-SQL的解决方案,但是如果不可能,那么我需要保持最小的往返行程。

  • 我打算将存在于另一个表中的值加在叶节点上。

    • Notice how there are no leaf nodes in the Parent column, and how the Child column only contains leaf nodes.
    • Ideally, I would like the results to be in the form of IEnumerable<IGrouping<Item, Item>> where the key is a Parent and the group items are all Children.
    • Ideally, I would like a solution that the entity provider can translate in to T-SQL, but if that is not possible then I need to keep round trips to a minimum.
    • I intend to Sum values that exist in another table joined on the leaf nodes.
    • 推荐答案

      由于你总是返回表中的所有项目,为什么不做一个递归方法来获取父项的所有子代,然后在内存中的项目中使用:

      Since you are always going to be returning ALL of the items in the table, why not just make a recursive method that gets all children for a parent and then use that on the in-memory Items:

      partial class Items
      {
          public IEnumerable<Item> GetAllChildren()
          {
              //recursively or otherwise get all the children (using the Hierarchy navigation property?)
          }
      }
      

      然后:

      var items = 
          from item in Items.ToList()
          group new 
          {
              item.itemID,
              item.GetAllChildren()
          } by item.itemID;
      

      对不起,任何语法错误...

      Sorry for any syntax errors...

      这篇关于递归林格集团的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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