Steve Nay
Steve Nay

Reputation: 2829

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

I'm building a two-dimensional array of data. I'd like to set the first row of this array to the contents of a one-dimensional array with the proper number of columns, like this:

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's 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'd like a simpler way to fill the first row rather than needing to iterate over each item like I do with the rows elements.

Is there a C# idiom for doing this?

Upvotes: 3

Views: 4270

Answers (1)

rodrigogq
rodrigogq

Reputation: 1953

You should 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++;
}

Upvotes: 1

Related Questions