-
Help with LINQ query
Hi!
I need to create a LINQ query that flattens a list of nested objects into a list that I can easily bind to a gridview.
The object hierarchy looks like this
Factory A
* Client 1
* CLient 2
Factory B
* CLient 3
* CLient 4
The factory is a very simple class, it has two properties a string property for Name and a List(of Client) called Clients. The Client class has three properties: string Name int Location and int Id
I want to create a flat list of anonymous objects that look like
FactoryName
ClientName
ClientId
ClientLocation.
I have spent the past hours trying to figure this out, and it should be really simple, like using the SelectMany() extension method, but I can't get the contexts in the LINQ query correct, so I can select both the name from the Factory class, and the other properties from the Client class.
help me out here!
thanks
Henrik
-
Re: Help with LINQ query
here's my solution:
Code:
Public Class Factory
Public Property Name As String
Public Property Clients As New List(Of Client)
End Class
Code:
Public Class Client
Public Property Name As String
Public Property Location As Integer
Public Property Id As Integer
End Class
Code:
Public Class Form1
Dim Factories As New List(Of Factory)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Factories.Add(New Factory With {.Name = "A"})
Factories.Last.Clients.Add(New Client With {.Name = "Client 1", .Id = 1, .Location = 101})
Factories.Last.Clients.Add(New Client With {.Name = "Client 2", .Id = 2, .Location = 111})
Factories.Add(New Factory With {.Name = "B"})
Factories.Last.Clients.Add(New Client With {.Name = "Client 3", .Id = 3, .Location = 121})
Factories.Last.Clients.Add(New Client With {.Name = "Client 4", .Id = 4, .Location = 131})
Dim datasource = (From f As Factory In Factories _
From c As Client In f.Clients
Select New With { _
.FactoryName = f.Name, _
.ClientName = c.Name, _
.ClientId = c.Id, _
.ClientLocation = c.Location}).ToArray
DataGridView1.DataSource = datasource
End Sub
End Class