4

Hello let me show you the problem with very simple explanation.

I have this;

int[] numbers1= { 1, 2, 3 };

and i need this;

int[] numbers2= { 1,1,1, 2,2,2, 3,3,3 };

how can i duplicate my values then use them in another list?

Martin Costello
  • 9,672
  • 5
  • 60
  • 72
  • 3
    Lets have a look at this without starting to write code. This is very plain logic and it seems you dont have the steps already planed and figured out. We need to take the values from numbers1, iterate each value x times and save them in the array numbers2. What steps do you need for that? What values will be important? – Cataklysim Apr 22 '22 at 09:20

4 Answers4

7

Try:

using System.Linq;

namespace WebJob1
{
    internal class Program
    {

        static void Main()
        {
            int[] numbers1 = { 1, 2, 3 };
            var numbers2 = numbers1.SelectMany(x => Enumerable.Repeat(x,3)).ToArray();
        }
    }
}
Mykyta Halchenko
  • 720
  • 1
  • 3
  • 21
2

You can try this:

    int multiplier = 3;
    int[] numbers1 = { 1, 2, 3 };

    var numbers2 = numbers1.SelectMany(x => Enumerable.Repeat(x, multiplier)).ToArray();

Maybe some useful information about LINQ extentions Select and SelectMany here.

Dominik
  • 300
  • 1
  • 14
2

You can do this with LINQ

var numbers2 = numbers1.SelectMany(x => new[]{x,x,x});

Live example: https://dotnetfiddle.net/FLAQIY

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

What about an algoritmic answer:

public class Program
{
    public static void Main()
    {
        int[] numbers1= { 1, 2, 3 };
        var numbers2 = ArrayMultiplier.MultiplyArray(numbers1, 3);  //{ 1,1,1,2,2,2,3,3,3 }
    }
    
    public static class ArrayMultiplier{
        public static int[] MultiplyArray(int[] array, int multiplicationCount){
            int[] result = new int[array.Length*multiplicationCount];
            for(int i =0; i<array.Length; i++){
                for(int j = 0; j<multiplicationCount; j++){
                    result[i*multiplicationCount + j] = array[i];
                }
            }
            return result;
        }
    }   
}
Husokanus
  • 13
  • 2