Home > Software design >  How to make two new arrays in C# from one, but not to Consol.writeline all null/ empty places in new
How to make two new arrays in C# from one, but not to Consol.writeline all null/ empty places in new

Time:12-08

I have to extract pozitiv end negativ numbers from one arrey in two new arrays. How to make two new arrays in C# from one, but not to Consol.writeline all null/ empty places in new arrays?

int[] array = { 12, 23, -22, -823,-4, 351, -999, 62 };

int[] arrayPozitivni = new int [array.Length];

int PozitivniCounter = 0;

for (int i = 0 ; i<array.Length ; i  )
{
    if (array[i] < 0 ) 
       
        {
        arrayPozitivni[PozitivniCounter] = array[i];
        PozitivniCounter  ;
    }
   
}
foreach (var item in arrayPozitivni)

      {
        Console.WriteLine(item);
    }

CodePudding user response:

LINQ can help here to make your life easier:

int[] arrayPositive = array.Where(i => i >= 0).ToArray();
int[] arrayNegative = array.Where(i => i  < 0).ToArray();

CodePudding user response:

int[] array = { 12, 23, -22, -823,-4, 351, -999, 62 };

List<int> positiveList= new List<int>();

List<int> negativeList= new List<int>();

for (int i = 0 ; i<array.Length ; i  )
{
    if (array[i] < 0 ) 
       
        {
          negativeList.Add(array[i]);
        }
        else
        {
          positiveList.Add(array[i]);
        }
   
}
int[] arrayPozitivni = positiveList.ToArray(); 
int[] arraynegative = negativeList.ToArray();

foreach (var item in arrayPozitivni)
{
        Console.WriteLine(item);
}

CodePudding user response:

Use a List<T> instead of an array. Unlike arrays, lists grow automatically when you add items.

List<int> listPozitivni = new List<int>();

Then you can add the items with

listPozitivni.Add(array[i]);

You can then use the foreach in the same way for the list as for the array to print the numbers.

But note that array[i] < 0 will return negative numbers, not positive ones.

CodePudding user response:

One good way is to use an ArrayList

using System;
using System.Collections;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {


            // I have to extract pozitiv end negativ numbers from one arrey in two new arrays.How to make two new arrays in C# from one, but not to Consol.writeline all null/ empty places in new arrays?

            int[] array = { 12, 23, -22, -823, -4, 351, -999, 62 };

            ArrayList arrayNegative = new ArrayList();

            int PozitivniCounter = 0;

            for (int i = 0; i < array.Length; i  )
            {
                if (array[i] < 0)

                {
                    arrayNegativ.Add( array[i]);
                    PozitivniCounter  ;
                }
              

            }
            foreach (var item in arrayPozitivni)

            {
                Console.WriteLine(item);
            }
        }
    }
}
  • Related