Home > Back-end >  how to copy a array in C#
how to copy a array in C#

Time:01-12

I try to take only positive numbers from the array and display them in the second array. I copy one array to another but at the output I get only 0. I’m a beginner in C#, so this is probably an easy thing to do

int[] array = { 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };
        int[] positive = new int[array.Length];
        int positiveCounter = 0;
        int[] source = new int[7];
        Array.Copy(positive, source, 7);
        for (int i = 0; i < array.Length; i  )
        {
            if (array[i] > 0)
            {
                positive[positiveCounter] = array[i];
                positiveCounter  ;
            }
        }
        Console.WriteLine("Positive numbers are: ");
        foreach (var item in positive)
        {
            Console.WriteLine(item);
        }

CodePudding user response:

You can query initial array with a help of Linq:

using System.Linq;

...
int[] array = ...

int[] positive = array.Where(item => item > 0).ToArray();

To show positive array in one go you can try string.Join:

Console.WriteLine(string.Join(", ", positive));

You can solve the problem with a help of loops (no Linq solution):

int[] array = ...

int positiveCounter = 0;

foreach (int item in array)
  if (item > 0)
    positiveCounter  = 1;

int[] positive = new int[positiveCounter];

int index = 0;

for (int i = 0; i < array.Length;   i)
  if (array[i] > 0)
    positive[index  ] = array[i];

please note, that Array.Copy copies consequent items which is not guaranteed.

CodePudding user response:

As your request it will take all the positive number from 1st array and store in second array

 static void Main(string[] args)
    {
        ArrayList array =new ArrayList{ 12, 23, -22, -765, 43, 545, -4, -55, 43, 12, 351, -999, -87 };
        ArrayList array2 = new ArrayList { };
        foreach(int item in array)
        {
            Console.WriteLine(item);
            if (item > 0)
            {
                array2.Add(item);
            }
        }
        Console.WriteLine("-----------------------------");
        foreach (int item in array2)
        {
            Console.WriteLine(item);
        }
    }
  •  Tags:  
  • Related