用一维数组填充一行二维数组

时间:2014-11-25 21:58:49

标签: c# arrays

我正在建立一个二维数据数组。我想将此数组的第一行设置为具有适当列数的一维数组的内容,如下所示:

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

基本上,我想要一种更简单的方法来填充第一行,而不是像我对rows元素那样迭代每个项目。

这样做是否有C#成语?

1 个答案:

答案 0 :(得分:1)

您应该更改语法:

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