分类: 嵌入式
2011-08-11 15:19:53
using System;
using System.Data;
namespace ArrayToDataTable
{
class ArrayToDataTable
{
///
/// 把一个一维数组转换为DataTable
///
/// 列名
/// 一维数组
///
public static DataTable Convert(string ColumnName, string[] Array)
{
DataTable dt = new DataTable();
dt.Columns.Add(ColumnName, typeof(string));
for (int i = 0; i < Array.Length; i++)
{
DataRow dr = dt.NewRow();
dr[ColumnName] = Array[i].ToString();
dt.Rows.Add(dr);
}
return dt;
}
///
/// 反一个M行N列的二维数组转换为DataTable
///
/// 一维数组,代表列名,不能有重复值
/// M行N列的二维数组
///
public static DataTable Convert(string[] ColumnNames, string[,] Arrays)
{
DataTable dt = new DataTable();
foreach (string ColumnName in ColumnNames)
{
dt.Columns.Add(ColumnName, typeof(string));
}
for (int i1 = 0; i1 < Arrays.GetLength(0); i1++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < ColumnNames.Length; i++)
{
dr[i] = Arrays[i1, i].ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
///
/// 反一个M行N列的二维数组转换为DataTable
///
/// M行N列的二维数组
///
public static DataTable Convert(string[,] Arrays)
{
DataTable dt = new DataTable();
int a = Arrays.GetLength(0);
for (int i = 0; i < Arrays.GetLength(1); i++)
{
dt.Columns.Add("col" + i.ToString(), typeof(string));
}
for (int i1 = 0; i1 < Arrays.GetLength(0); i1++)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < Arrays.GetLength(1); i++)
{
dr[i] = Arrays[i1, i].ToString();
}
dt.Rows.Add(dr);
}
return dt;
}
}
}