Home > Net >  Are there better ways to split arrays into smaller arrays?
Are there better ways to split arrays into smaller arrays?

Time:11-24

I have a program that will create orders for a bunch of orders. However API has limitation that if I wanna do that I got to do it 10 at a time

If orderList.Count > 10 Then
    Dim FirstTwenty = From n In orderList Take (10)
    Dim theRest = From n In orderList Skip (10)
    Dim result1 = Await internalActualcreateNormalLimitOrderMultiple(FirstTwenty.ToArray)
    Dim result2 = Await internalActualcreateNormalLimitOrderMultiple(theRest.ToArray)
    Return result1   result2 'no longer json but we don't really use the resulting json unless for debugging
End If

Basically I want to split {1,2,3,4,5,6,7,8,9,10.11.12,...} into {1,2,3}{4,5,6},{7,8,9},...

And I wonder if I can use linq instead of for each

So I use this recursive function. Get first 10 or twenty and then recursively call the function and so on.

And I look at it and while it's simple, it doesn't seem right. Obviously number of orders won't be big. At most 15. But what about if on day I have 100? I can get like stackoverflow for recursive things.

If only there is a function that can split arrays into array using linq, where, take, and skip that'll be great.

Of course I can do for each but perhaps there is a more elegant way?

Then I wrote another code

Public Shared Function splitArrayIntoSmallerArrays(Of someObject)(arrayOfSomeObject As someObject(), chunkSize As Integer) As List(Of someObject())
    Dim output = New List(Of someObject())
    Dim newestArray = New List(Of someObject)
    For i = 0 To arrayOfSomeObject.Count - 1

        newestArray.Add(arrayOfSomeObject(i))
        If newestArray.Count = chunkSize Then
            output.Add(newestArray.ToArray)
            newestArray = New List(Of someObject)
        End If
    Next
    output.Add(newestArray.ToArray)
    Return output
End Function

That'll do it in O(n)

But I think it can be done more simply by using linq, seek, and take but I don't know how. Or may be group by.

Any idea?

CodePudding user response:

Your question was not very clear to me, but I believe you have an array with several "objects" inside it, correct? And before that you want to divide this matrix into smaller matrices, correct?

So how about passing this larger matrix to a JSON, creating an object that will be filled in by the smaller values ​​and then transforming this JSON again into objects of the type above, then passing these objects to the smaller array, do you understand?

CodePudding user response:

If you have access to Net 7.0, perhaps you're looking for Enumerable.Chunk?

Splits the elements of a sequence into chunks of size at most size.

  • Related