❔ Combine two arrays by alternating items?
Let's imagine I have two arrays, A and B, which each have four items.
I want to make a new array C which is made up of the contents of A and B.
so
Except can I do this with LINQ? And for any arbitrary size?
22 Replies
it is possibile to do with LINQ but a for loop will be the clearest and easiest way, by far
In my use case, the two source arrays are of equal size ... I'm not sure what I'd want this method to do in the case of arrays of different sizes
How about this maybe?
That one should keep going until it runs out of items from the first array, and it assumes that all the arrays after the first array will have at least as many items as the first array.
Is that how params works
I think so yeah
params is basically an array of a type
I was referring to params having to be a single dimensional array
But i could be wrong
I know this works because I have used it before:
thats what I said yea
No, params can be a multi dimensional array. You can call the method with a multi dimensional array of that same size or you can call it with multiple parameters of one dimension smaller arrays.
However, from looking at this, I strongly suspect I constructed my for loops incorrectly
Okay so, you have a varying number of arrays of different length
Oh wait, no I didn't, I used z
And you want to combine them into one array with alternating values inserted
Yeah but I updated to specify that all arrays after the first one must be equal to or greater than the first one's in length. That makes my code simpler.
right
How so? You can still have varying array lengths, you just have a minimum size now
right
Basically you wanna loop through the list of arrays, adding the first unused value to the resulting array
Might be easier to use a List to hold the values then you could ToArray it at the end (that’s a function right?)
I think I should change that one line to
result[z + y] = list[y][x];
How would that helpCus you wouldn’t really have to worry about what index the result would be
Just call result.Add
As long as you get the order right
The thing is going from your example you could have, for example 5 arrays, of respective lengths of 4, 4, 6, 4, 7. You would have to do some bounds checking
I managed to confirm it works with a unit test.
Well no, I'd just have to document the requirement about array sizes, which I did with a comment.
This is actually being used in a situation where all the arrays will always be of equal size
Oh that makes it easier then
Just loop through the list of arrays adding the value of the value at the first unused index
Ig you could use a nested loop
I don’t know how you’d do it with LINQ though
That's what I did in that template method I posted
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.