Home > Enterprise >  Putting two 1D arrays into one 2D array in c#
Putting two 1D arrays into one 2D array in c#

Time:10-03

Hey guys i have two 1D arrays one with names and one with phonenumbers:

private string[] names = { "xaw",       "Tommy",     "Alan",   "Sergio",    "Adam",     "Pablo" };
private string[] phones = { "535-4213", "535-0421", "722-352", "070-3531", "343-2324", "344-2223" };

I want to put them into one 2D array. also do i have to declare array size like this:

string[,] phonesNames = new string[6,2] 

or can i leave it like this: (without declaration of size? Will it work in this case?)

string[,] phonesNames; 

The result should be pairs so phoneNames[0,0] is xaw and phoneNames[0,1] is 535-4213 like this:

Xaw 535-4213
Tommy 535-0421
Alan 722-352
Sergio 070-3531
Adam 343-2324
Pablo 344-2223

I would greatly appreciate if you helped me please.

@edit This is actually not the solution because it only appears as sorted with Console.Writeline() the array is now [2,6] but the thing i was searching for was sorted array [6,2]

private static void Main(string[] args)
    {
        string[] names = { "xaw", "Tommy", "Alan", "Sergio", "Adam", "Pablo" };

        string[] phones = { "535-4213", "535-0421", "722-352", "070-3531", "343-2324", "344-2223" };


        string[,] phonesNames = new string[2, names.Length];
        for (var i = 0; i < names.Length; i  )
        {
            phonesNames[0, i] = names[i];
            phonesNames[1, i] = phones[i];
        }

        for (int i = 0; i < names.Length; i  )
            Console.WriteLine("{0} {1}", phonesNames[0,i], phonesNames[1,i]);
    }
}

The solution is in just 2 lines of code in for loop

for (int dimension = 0; dimension < 6; dimension  )
            {
                phonesNames[dimension, 0] = names[dimension]; 
                phonesNames[dimension, 1] = phones[dimension];
            }

CodePudding user response:

enter image description hereenter image description here

string[] names = { "xaw", "Tommy", "Alan", "Sergio", "Adam", "Pablo" };

string[] phones = { "535-4213", "535-0421", "722-352", "070-3531", "343-2324", "344-2223" };

string[][] phoneNames = new string[2][];

phoneNames[0] = names;

phoneNames[1] = phones;

for (int i = 0; i < names.Length; i  )

    Console.WriteLine("{0} {1}", phoneNames[0][i], phoneNames[1][i]);


  [![enter image description here][1]][1]

CodePudding user response:

Also, you can use ZIP Method
(enter image description here

To access a specific cell, you simply use:

Console.WriteLine(phonesNames[0,2]); // Alan

To access a whole column, e.g. 4th column:

var column4 = GetColumn(phonesNames, 4);
Console.WriteLine(string.Join(" ", column4));
// output = Adam 343-2324
  • Related