LINQ to Objects - 祖父母,父母,子女关系

时间:2010-02-03 15:44:07

标签: vb.net linq linq-to-objects

我是LINQ的新手,我已经能够编写一些简单的语句了。但现在我有一个更复杂的情况,我无法弄清楚。

基本上,我正在尝试编写一个LINQ to Objects语句,其中的关系是祖父母,父母,子女关系。 (你也可以称之为Master Detail关系。)

在Legacy代码中,这是我想要完成的简化版本。

        Dim coverages As New List(Of Coverage)
        Dim coverage As Coverage 

        For Each rl In oClaimsPolicy.RiskLocations 

            coverage = New Coverage
            coverage.Level = "Location"

            'Get rl detail detail
            coverages.Add(coverage) 

            For Each ri In rl.RiskItems 

                coverage = New Coverage
                coverage.Level = "Item"

                'Get ri detail
                coverages.Add(coverage) 

                For Each rc In ri.RiskCoverages 

                    coverage = New Coverage
                    coverage.Level = "Coverage"

                    'Get rc detail here
                    coverages.Add(coverage) 

                Next 

            Next 

        Next

如果不清楚一个Location可以有多个Items而一个Item可以有多个Coverages。我基本上想要列出项目并显示祖父母(位置),父母(项目)和孩子(覆盖范围)之间的关系。

更新

以下是我提出的建议:

Dim coverages = oClaimsPolicy.RiskLocations. _
                  SelectMany(Function(rl) rl.RiskItems. _
                  SelectMany(Function(ri) ri.RiskCoverages. _
                  Select(Function(rc) New Coverage With {.Level = "Coverage"})))

然而,这只列出了所有的孩子(Coverages)。

这是我要找的结果:

Location
    Item 
       Coverage 
    Item 
       Coverage 
       Coverage 
Location 
    Item 
       Coverage 

因此,数据按位置和项目分组。

查看它的另一种方法是ListView或Report。分组由位置和项目完成的位置。

示例如下所示

Location
    Item
        Coverage
    Item
        Coverage
        Coverage
Location
    Item
        Coverage

这是清楚的吗?

1 个答案:

答案 0 :(得分:0)

我去测试时你的原始查询没有编译。这是一个版本:

Dim coverages = _
    From rl In oClaimsPolicy.RiskLocations _
    From ri in rl.RiskItems _
    From rc in ri.RiskCoverages _
    Select New Coverage With {.Level = "Coverage"}

现在,要获得您想要的结果,请尝试这样做:

dim create As Func(Of String, IEnumerable(Of Coverage)) = _
    Function (level) New Coverage() _
        { New Coverage With { .Level = level } }

Dim coverages = _
    From rl In oClaimsPolicy.RiskLocations _
    From cl In create("Location").Concat( _
            From ri In rl.RiskItems _
            From ci In create("  Item").Concat( _
                    From rc In ri.RiskCoverages _
                    From cc In create("    Coverage") _
                    Select cc) _
            Select ci) _
    Select cl

这是一堆嵌套的SelectMany& Concat个表达式,它会生成Coverage个对象的列表,如下所示:

Location
  Item
    Coverage
Location
  Item
    Coverage
  Item
    Coverage

这就是你要追求的吗?