简体   繁体   中英

Repeat values for n times

I have a collection of values

[1, 4, 23, 90]

and these values should be stored into a array repeated 3 times without using Linq

[1, 1, 1, 4, 4, 4, 23, 23, 23, 90, 90, 90]

what I've tried so far

int[] collection = { 1, 4, 23, 90 };
int multiplier = 3;
int[] result = new int[collection.Length * multiplier];
for (int i = 0; i < collection.Length; i++)
    for (int j = 0; j < multiplier; j++)
        result[i + j] = collection[i];

but somehow only the first 6 fields of the array are filled

If you are not looking for a Linq solution,

Insert duplicates values linq

then just compute which item to put into result : i -th result 's item corresponds to i / multiplier collection s one

int[] collection = new int[] { 0, 2, 25, 30 };
int multiplier = 3;
int[] result = new int[collection.Length * multiplier];

for (int i = 0; i < result.Length; i++)
  result[i] = collection[i / multiplier];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM