如何在C#中将DataTable转换为Array?

时间:2019-07-17 03:54:16

标签: c#

我想将picker.addEventListener('ionPickerColChange', async (event: any) => { here handle some logic } 中的DataTable datatable1转换为Multidimensional Array

C#

我想将其转换为| Name | Age | ------------------ | jim | 23 | | ard | 22 | | tom | 30 | 。 有人可以帮我吗?谢谢。

2 个答案:

答案 0 :(得分:1)

应该是:

string[,] str = new string[YourDataTable.Rows.Count, 2]; 

int i = 0;
foreach (DataRow row in YourDataTable.Rows)
{
    if (i < YourDataTable.Rows.Count)
    {
        str[i, 1] = row["name"].ToString();
        str[i, 2] = row["age"].ToString();
        i++;
    }
}

答案 1 :(得分:0)

var datatable1 = CreateDataTable(); // or the way you populate the table
var data = datatable1.Rows
                     .Cast<DataRow>()
                     .Select(row => row.ItemArray)
                     .ToArray();
Console.WriteLine(DataToString(data));

CreateDataTable()在哪里

DataTable CreateDataTable()
{
    var dt = new DataTable("tbl");
    dt.Columns.AddRange(new DataColumn[]
    {
        new DataColumn("Name", typeof(string)),
        new DataColumn("Age", typeof(int))
    });
    dt.Rows.Add("Jim", 23);
    dt.Rows.Add("Ard", 22);
    dt.Rows.Add("Tom", 30);
    return dt;
}

DataToString(object[][] data)

string DataToString(object[][] data) =>
    $"[{string.Join(", ", data.Select(i => $"[{string.Join(", ", i)}]"))}]";

给予

[[Jim, 23], [Ard, 22], [Tom, 30]]