How to Split a List into Sublists of size N in Business Central

The following post is related to how to divide a List into several sublists given size in Business Central.

I recently had a case where I was asked to build a process that consumes a third-party API in order to upload a JSON file.

It turns out, that for some reason, to process a JsonArray with more than 50 elements, the API took more than 5 minutes to respond and in Business Central the maximum Timeout that can be configured in the HttpClient is 300,000 milliseconds, which is 5 minutes otherwise it also gives error.

In view of the above, a quick solution that occurred to me was to partition the data and send it fractionally, for this I used a list of lists and that is what I want to share with you today.

Code

The following procedure is the protagonist of the post, it allows dividing a List in this case of JsonObject into sublists of size Size.

To make the operation of this method a little practical and simple, I have created a small module that creates a JsonObject with all the Posted Sales Invoices, and then, through the previously shown function, I create PostedSalesInvoicePack, which would be the List of several Sublists of JsonObjects generated from the Posted Sales Invoices.

Below I share all the Helper codeunits created for the post.

Tests

The elements were fractioned in size by 25.

The following image is what the List of Lists looks like in the debugger.

Conclusion

Thanks to Split List into Sublists, scenarios like the one presented to me could help to partition the data that is trying to be sent to avoid Timeouts generated in the HttpClient of Business Central.

All the code used can be found at the following github link.

I hope this is useful.

Leave a Reply

Your email address will not be published. Required fields are marked *