Ayyappa
Ayyappa

Reputation: 33

Array of values into formation of matrix c#

Hi In my requirement i have array of values(1 to 12) i want to do that array values into formation of matrix example. i want like that output i tried but i get repeated rows please solve this problem.

Expected output is:

 A  B  C  D 
 1  2  3  4
 5  6  7  8
 9  10 11 12
 13 14 15 16

Code that I'm using

 DataTable dt = new DataTable();
    dt.Columns.Add("Col1");
    dt.Columns.Add("Col2");
    dt.Rows.Add("A", "1");
    dt.Rows.Add("B", "2");
    dt.Rows.Add("C", "3");
    dt.Rows.Add("D", "4");
    dt.Rows.Add("A", "5");
    dt.Rows.Add("B", "6");
    dt.Rows.Add("C", "7");
    dt.Rows.Add("D", "8");
    dt.Rows.Add("A", "9");
    dt.Rows.Add("B", "10");
    dt.Rows.Add("C", "11");
    dt.Rows.Add("D", "12");
    dt.AcceptChanges();
    int[] intArray = new int[10];
    DataTable dt2 = new DataTable();
    for (int i = 0; i <= dt.Rows.Count; i++)
    {
        if (!(dt2.Columns.Contains(dt.Rows[i][0].ToString())))
        {
            dt2.Columns.Add(dt.Rows[i][0].ToString());
        }
        else
            break;
    }
    int x = 0;
    int m = 0;
    for (int j = x; j < dt.Rows.Count; j++)
    {
        // create a DataRow using .NewRow()
        DataRow row = dt2.NewRow();
        int i = 0;
        // iterate over all columns to fill the row
        for (i = 0; i < dt2.Columns.Count; i++)
        {
            row[i] = dt.Rows[i][1];
            x = i;
        }
        // add the current row to the DataTable
        dt2.Rows.Add(row);
    }

Upvotes: 2

Views: 328

Answers (1)

sujith karivelil
sujith karivelil

Reputation: 29016

Forgive me if i misunderstand your requirements. it is not clear from the question and you ware not willing to add more info. The specified output looks like a DataTable with headers as A,B,C,D if so you can try the following code:

int[] inputElements = Enumerable.Range(1, 12).ToArray(); // Will give you array(1-12)
DataTable outputTable = new DataTable();
outputTable.Columns.Add("A");
outputTable.Columns.Add("B");
outputTable.Columns.Add("C");
outputTable.Columns.Add("D");
for (int i = 0; i < inputElements.Length - 1; )
{
    DataRow dRow = outputTable.NewRow();
    for (int j = 0; j < 4; j++)
    {
        dRow[j] = inputElements[i];
        i++;
    }
    outputTable.Rows.Add(dRow);
}

The out put table will be like this:

enter image description here

Upvotes: 1

Related Questions