# Form a matrix using MySql data in C#

I have a Table in MySQL with thousands rows of data and 3 columns as follows: Column1:Hour(in int), Column2:DayOfWeek(in int), Column3:Power(in double)

How do I form a (thousands rows x 3)matrix in C# console application? In addition, how do I do a transpose on the matrix? Below shows part of my code:

List<double> realPowers = new List<double>(); List<int> dayOfWeek = new List<int>(); List<int> Hour = new List<int>(); int rows_count = 0; using (MySqlDataReader myReader = cmdDatabase.ExecuteReader()) { foreach (DbDataRecord record in myReader) { realPowers.Add(record.GetDouble(3)); dayOfWeek.Add(record.GetInt32(2)); Hour.Add(record.GetInt32(1)); rows_count++; } } double[] Load = realPowers.ToArray(); int[] X = dayOfWeek.ToArray(); int[] Y = Hour.ToArray(); int[][] matrix = new int[3][]; for (int i = 0; i < matrix.Length; i++) { matrix[i] = new int[rows_count]; } matrix[0] = X;

I am able to form each individual column of data into a single column matrix. But how do I combine the 3 columns of data into a matrix of 3 columns? Thank you!

## Answers

You can do it in two ways:

int[][] matrix = new int[3][];

or

int[,] matrix = new int[3,1000];

As your Power is double, you may use type double for everything.

If using the first construct you need to do a loop and initialize your elements.

for (int i = 0; i < matrix.Length; i++) { matrix[i] = new int[1000]; }

The first construct is called jagged array (or array of arrays)

http://msdn.microsoft.com/en-us/library/2s05feca.aspx

The second construct is called multidimensional array.

http://msdn.microsoft.com/en-us/library/2yd9wwz4.aspx

Regarding transposing see this example.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace ConsoleApplicationTEST { class Program { static void Main(string[] args) { int[,] matrix = new int[5, 8] { { 1, 2, 3, 4, 5, 6, 7, 8 }, { 9, 10, 11, 12, 13, 14, 15, 16 }, { 17, 18, 19, 20, 21, 22, 23, 24 }, { 25, 26, 27, 28, 29, 30, 31, 32 }, { 33, 34, 35, 36, 37, 38, 39, 40 }, }; int[,] newArray = new int[8, 5]; for (int j = 0; j < 8; j++) for (int r = 0; r < 5; r++) newArray[j, r] = matrix[r, j]; for (int r = 0; r < 8; r++) { for (int c = 0; c < 5; c++) { Console.Write(newArray[r,c] + " "); } Console.WriteLine(); } Console.ReadLine(); } } }