我正在建立一个二维数据数组。我想将此数组的第一行设置为具有适当列数的一维数组的内容,如下所示:
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#成语?
答案 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++;
}