Datatable常用系列一
一、用作集合存储数据:
DataTable dt = new DataTable("action");
for (int i = 0; i < 10; i++)
{
dt.Columns.Add("action" + i);
}
for (int i = 0; i < dt.Columns.Count; i++)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < 10; j++)
{
dr[j] = j;
}
dt.Rows.Add(dr);
}
二、利用扩展方法AsEnumerable对集合进行刷选
decimal action9_Sum = dt.AsEnumerable().Sum(x => Convert.ToDecimal(x["action9"]));
//....原型:
decimal sum = 0m;
foreach (DataRow item in dt.Rows)
{
if (item["action9"] != null)
sum += decimal.Parse(item["action9"].ToString());
}
List<object> list = dt.AsEnumerable().Select(x => x["action9"]).ToList();
三、利用dataview进行刷选
DataTable dt3 = new DataView(dt)
{
Sort = "action9",
}.ToTable();
DataTable dt4 = new DataView(dt)
{
RowFilter = "action0='9'",
}.ToTable();
四、group by:举例
var d3 = d1.AsEnumerable().GroupBy(x => new { t1 = x.Field<string>("time"), t2 = x.Field<string>("str1") })
.Select(x => new { time = x.Key.t1, str0 = x.Key.t2, c = x.Count() });
group by 前:
group by 后:
五、Xml转换
string xml = "<?xml version="1.0" encoding="UTF-8"?><root><a>1</a><b>2</b></root>";
DataSet ds = new DataSet();
StringReader sr = new StringReader(xml);
ds.ReadXml(sr);
DataTable dt5 = ds.Tables[0];
六、未完待续...