LINQ to Objects - Grandma, Grandpa, Parent, Children

I am new to LINQ, and I have managed to write some simple statements. But now I have a more difficult situation that I cannot understand.

Basically, I'm trying to write a LINQ to Objects statement, where relationships are relationships between grandfather, parent, and child. (You can also call it the Master Part relationship.)

The Legacy code shows a simplified version that I'm trying to execute.

        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

If it is not clear that one Locationcan have a lot Items, and one Itemcan have a lot Coverages. I basically want to list the elements and show the relationship between Grandparents (Location), parent (Item) and child (Coverage).

Update:

Here is what I came up with:

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

However, it just listed all the children (Covers).

, :

Location
    Item 
       Coverage 
    Item 
       Coverage 
       Coverage 
Location 
    Item 
       Coverage 

, .

- ListView Report. .

Location
    Item
        Coverage
    Item
        Coverage
        Coverage
Location
    Item
        Coverage

?

+3
1

, . , :

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

, ?

0

Source: https://habr.com/ru/post/1731231/


All Articles