Page 1 of 1

Using Linq for simpler, maintainable code

PostPosted: Tue Mar 24, 2015 7:30 am
by Mike.Sheen
Linq is a pretty powerful tool in .NET. It can make your code much cleaner, neater and simpler - thus more maintainable.

Here's an example I came up with to show on saving a sales order the sum of deliveries grouped by classification.

You will need to add a reference to System.Linq and also the following Imports:

Code: Select all
Imports System.Linq


Code: Select all
Public Sub Salesorder_saving(sender As Object, e As System.EventArgs)
   Dim salesOrder As JiwaSales.SalesOrder.SalesOrder = sender
   
   Dim queryResults = From salesOrderLine In salesOrder.SalesOrderLines
   Where salesOrderLine.CommentLine = False
   Group salesOrderLine By salesOrderLine.ClassificationDescription
   Into TotalDelivered = Sum(CInt(salesOrderLine.QuantityThisDelivery))
   Select ClassificationDescription, TotalDelivered
   
   For Each queryResult As Object In queryResults
      MsgBox(String.Format("Classification '{0}' has {1} total deliveries", queryResult.ClassificationDescription, queryResult.TotalDelivered))
   Next
   
End Sub


As you can see, this is quite a bit simpler than the conventional approach of iterating through each line, adding to a new list based on uniqueness of the classification and keeping a tally.

A plugin containing the above is attached.
Plugin Linq Sample.xml
Sample Plugin
(33.77 KiB) Downloaded 281 times