23.2. Old-School Queries
Instead of walking through exactly what LINQ is, let's start with an example that will demonstrate some of the savings that these queries offer. The scenario is one in which a researcher is investigating whether or not there is a correlation between the length of a customer's name and the customer's average order size. The relationship between a customer and the orders is a simple one-to-many as shown in Figure 23-2.
Figure 23.2. Figure 23-2
In the particular query we are examining, the researchers are looking for the average Milk order for customers with a first name greater than or equal to five characters, ordered by the first name:
Private Sub OldStyleQuery()
Dim customers As Customer() = BuildCustomers()
Dim results As New List(Of SearchResult)
Dim matcher As New SearchForProduct("Milk")
For Each c As Customer In customers
If c.FirstName.Length >= 5 Then
Dim orders As Order() = Array.FindAll(c.Orders, _
AddressOf matcher.ProductMatch)
Dim cr As New SearchResult
cr.Customer = c.FirstName & " " & c.LastName
For Each o As Order In orders
cr.Quantity += o.Quantity
cr.Count += 1
Next
results.Add(cr)
End If
Next
results.Sort(New Comparison(Of SearchResult)(AddressOf CompareSearchResults))
ObjectDumper.Write(results)
End Sub
Before we jump in and show how LINQ can improve this snippet, let's examine how this snippet works. The opening line calls out to ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access