2016-04-21 76 views
1

有一个类型A的列表,每个列表都包含一个B类型的列表,获取所有类型B的列表的最佳方式是什么?每个列表都包含它们所属的类型A的列表?在LINQ中反转嵌套集合

拥有一个像列表如下:

var parents = new List<Parent> { 
    { 
     new Parent { 
      ID = 1, 
      Childs = new List<Child> { 
       { 
        new Child { 
         ID = 1 
        } 
       }, 
       { 
        new Child { 
         ID = 2 
        } 
       }, 
       { 
        new Child { 
         ID = 3 
        } 
       } 
      } 
     }      
    }, 
    { 
     new Parent { 
      ID = 2, 
      Childs = new List<Child> { 
       { 
        new Child { 
         ID = 3 
        } 
       }, 
       { 
        new Child { 
         ID = 4 
        } 
       }, 
       { 
        new Child { 
         ID = 5 
        } 
       } 
      } 
     }      
    } 
}; 

我想查询此获得以下结果:

[ 
    { 
    Child = 1, 
    InParent = [1] 
    }, 
    { 
    Child = 2, 
    InParent = [1] 
    }, 
    { 
    Child = 3, 
    InParent = [1, 2] 
    }, 
    { 
    Child = 4, 
    InParent = [2] 
    }, 
    { 
    Child = 5, 
    InParent = [2] 
    }, 
] 

编辑:我想首先拼合孩子的一种方法使用SelectMany & Distinct,但不知道如何将其再次链接到父级:

var foo = 
    from childId in parents.SelectMany(x => x.Childs).Select(x => x.ID).Distinct() 
    select 
     new 
     { 
      childId = childId, 
      inParent = // Missing Part 
     }; 
+2

在问一个问题之前,你有尝试过什么吗?你有什么问题? – wudzik

+0

当然,我试图用SelectMany/Distinct扁平孩子,它返回所有涉及孩子的清单,但没有连接到他们所属的父母。当然,我可以循环遍历它,我的问题是如何在LINQ查询中实现这一点。 –

回答

4

你必须使用SelectMany先展平,然后,再由孩子-ID使用GroupBy分组和String.Join到Concat的每个父ID:

var childParents = parents 
    .SelectMany(p => p.Childs.Select(c => new {Parent = p, Child = c})) 
    .GroupBy(x => x.Child.ID) 
    .Select(g => new 
    { 
     Child = g.Key, 
     InParent = String.Join(", ", g.Select(x => x.Parent.ID)) 
    }); 

结果:

enter image description here

如果你不想InParent属性是一个字符串,但是List<int>(或数组)使用这个:

..... 
InParent = g.Select(x => x.Parent.ID).ToList() // or ToArray() 
0

您可以分割你的大问题分成两个简单的问题:

  1. 每个父/子对创建一个匿名的对象,包含的母公司,以及对孩子的引用。你可以使用一个简单的LINQ查询和两个from子句。

  2. 将这些对象分组到您需要的表示中。 group by条款是你的朋友在这里。

-1

我想你应该尝试改变你的数据模型,如果你正在寻找存储树状结构,在那种情况下你应该总是使用与自定义对象单链表&嵌套参考类似相应的父/子你存储在数据库中的方式。

这是一种理想的方式来处理这样的数据结构,否则您将最终在许多嵌套查询。