Fill one row of a two dimensional array with a one dimensional array

I am creating a 2D dataset. I would like to set the first row of this array to the contents of a one-dimensional array with the appropriate number of columns, for example:

private string[] GetHeaders() {
    return new string[] { "First Name", "Last Name", "Phone" };
}

private void BuildDataArray(IEnumerable<Person> rows) {
    var data = new string[rows.Count() + 1, 3];

    // This statement is invalid, but it roughly what I want to do:
    data[0] = GetHeaders();

    var i = 1;
    foreach (var row in rows) {
        data[i, 0] = row.First;
        data[i, 1] = row.Last;
        data[i, 2] = row.Phone;
        i++;
    }
}

      

Basically, I want an easier way to populate the first row, rather than iterating over each element as I do with elements rows

.

Is there a C # idiom for doing this?

+3


source to share


1 answer


You must change your syntax:



var data = new string[rows.Count()][];

// This should be valid, an array of arrays
data[0] = GetHeaders();

var i = 1;
foreach (var row in rows) {
    data[i][0] = row.First;
    data[i][1] = row.Last;
    data[i][2] = row.Phone;
    i++;
}

      

0


source







All Articles