Using Linq for simpler, maintainable code

Samples and Examples of using the Jiwa 7 framework - including plugins, stand-alone applications and scripts.

Using Linq for simpler, maintainable code

Postby Mike.Sheen » Tue Mar 24, 2015 7:30 am

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 98 times
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2444
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 756

Return to Samples and Examples

Who is online

Users browsing this forum: No registered users and 1 guest

cron