3

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?

4
  • 3
    Any particular reason you are using arrays? This is simple with List<T>. Commented Nov 25, 2014 at 22:00
  • 1
    It would be easy if you used jagged array instead of multidimensional one. Commented Nov 25, 2014 at 22:03
  • @BradleyDotNET I need to pass the array to some existing code that only accepts object[,]. I will probably rewrite that function to use List<T> since it would make a lot of things easier, but first I'm curious whether this is possible. Commented Nov 25, 2014 at 22:06
  • Fair enough. I don't think there is, but I've been wrong before :) Commented Nov 25, 2014 at 22:06

1 Answer 1

1

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++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

We should note that you must initialize data[i] on every iteration of the foreach (not necessary before), but otherwise this code does what I need. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.