C#的datatable使用

2021-06-12 03:06

阅读:598

标签:close   nbsp   csv   table   test   mod   obj   文件   each   

// 构造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 

 

C#的datatable使用

标签:close   nbsp   csv   table   test   mod   obj   文件   each   

原文地址:https://www.cnblogs.com/ycz0926/p/10520866.html


评论


亲,登录后才可以留言!