Feb
21
Written by:
Steve Gray
2/21/2011 3:24 PM
I’m… just not a big fan of LINQ. It’s hard to work with, the syntax is obscure and it’s hard to find documentation for. I’m not sure if it’s something that will be around in the future.
Anyway, I have this task that reoccurs every so often – given a DataTable, I need to group the table by one (or more) of the fields and do something with the group. Often I need to iterate through the lines in the table that match a group.
Note that the first query returns one field, so when you reference that field in ‘salesQueryItem’, you only need strTo = salesQueryItem. In the second loop there is more than one field in the select, so they’re itemized.
Code Snippet
- Dim oDT As New DataTable
-
- 'create columns
- oDT.Columns.Add(New DataColumn("salesperson", System.Type.GetType("System.String")))
- oDT.Columns.Add(New DataColumn("order", System.Type.GetType("System.String")))
- oDT.Columns.Add(New DataColumn("amount", System.Type.GetType("System.Int16")))
-
- 'create the rows
- oDT.Rows.Add("Bob@test.com", "ORD00100", 1.23)
- oDT.Rows.Add("Bob@test.com", "ORD00102", 3.23)
- oDT.Rows.Add("Sam@test.com", "ORD00104", 2.23)
- oDT.Rows.Add("Sam@test.com", "ORD00105", 4.23)
-
-
- Dim strBody As String = ""
- Dim strTo As String = ""
- Dim strSubject As String = "Product Hold Email Notification"
-
- Try
- Dim salesQuery = From sales In oDT _
- Group sales By salesperson1 = sales("salesperson") Into Group _
- Select salesperson1 = salesperson1
-
-
- For Each salesQueryitem In salesQuery
- strTo = salesQueryitem
- strBody = "Orders for " & strTo & "<br />"
-
- Dim Query2 = From emailNotifications In oDT _
- Where emailNotifications("salesperson") = strTo _
- Select order1 = emailNotifications("order"), amount1 = emailNotifications("amount").ToString
-
- For Each Query2item In Query2
- strBody += Query2item.order1 + "<br />"
- strBody += "Amount: " & Query2item.amount1 + "<br />"
- Next
-
- 'code to send an email here
- Next
-
- Catch ex As Exception
- MsgBox(ex.Message)
- End Try
As always, I welcome your comments!