// 构造datatable
DataTable dt = new DataTable("test_table");
dt.Columns.AddRange(new DataColumn[]{
new DataColumn("name", typeof(string)),
new DataColumn("sex", typeof(string)),
new DataColumn("score", typeof(int))
});
dt.Rows.Add(new Object[] {"张三", "男", 1});
dt.Rows.Add(new Object[] {"张三", "男", 4});
dt.Rows.Add(new Object[] {"李四", "男", 100});
dt.Rows.Add(new Object[] {"张三", "女", 90});
dt.Rows.Add(new Object[] {"王五", "女", 77});
Console.WriteLine(dt.Rows[0]["name"]);
Console.WriteLine(dt.Rows[0]["sex"]);
dt.Rows[0]["score"] = 80;
Console.WriteLine(dt.Rows[0]["score"]);
Console.WriteLine(dt.TableName);
Console.WriteLine("test_table has " + dt.Rows.Count + " rows");
// 行内查找
DataRow[] rows = dt.Select("name=" + "'张三'" + "and sex=" + "'男'");
DataTable temp = dt.Clone();
foreach (DataRow row in rows)
{
Console.WriteLine(row["name"]);
temp.Rows.Add(row.ItemArray);
}
// 统计
Console.WriteLine(temp.Compute("sum(score)", ""));
Console.WriteLine();
// datatable的copy和clone
DataTable dt2 = dt.Copy();
Console.WriteLine(dt2.Rows.Count);
Console.WriteLine(dt2.Rows[0]["score"]);
DataTable dt3 = dt.Clone();
dt3.Rows.Add(new object[] {"abc", "女", 80});
dt3.Rows.Add(new object[] {"drt", "男", 90});
// 构造新行
DataRow dr = dt3.NewRow();
dr[0] = "jkj";
dr[1] = "女";
dr[2] = 100;
dt3.Rows.Add(dr);
Console.WriteLine(dt3.Rows.Count);
// 写入csv文件
if (File.Exists(dt.TableName + ".csv"))
{
File.Delete(dt.TableName + ".csv");
}
FileStream fs = new FileStream(dt.TableName + ".csv", FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
var data = string.Empty;
for (var i = 0; i < dt.Columns.Count; i++)
{
data += dt.Columns[i].ColumnName;
if (i < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
for (var i = 0; i < dt.Rows.Count; i++)
{
data = string.Empty;
for (var j = 0; j < dt.Columns.Count; j++)
{
data += dt.Rows[i][j].ToString();
if (j < dt.Columns.Count - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
sw.Close();
fs.Close();
Console.ReadKey();