DataTable進階操作

有些時候我們要進行一些數據的運算很難由SQL語法直接串出來,必須透過迴圈的方式算出有用的數據來使用,而DataTable本身就又提供一些我們平常比較少用的語法,下面我就針對這些方式進行介紹,目前只先使用幾種後來要是我在有用到在繼續補充在本文。
例1 : 資料庫撈出2011/05/01~2011/06/01這一段區間的紀錄,資料列的欄位包含了日期、經度、緯度等...,我們有一個需求就是要將每天(或者可以週、月方式都一樣)的總里程顯示出來,這時候我們就可以將資料先塞入DataTable後,在使用類似SQL Distinct的方式將目前資料表內有多少日期找出來進行下一部的運算。
//tempdt是一個DataTable
DataView tempview = tempdt.DefaultView;
//date為日期欄位,格式yyyy/MM/dd,此功能類似SQL Distinct
DataTable tempdt1 = tempview.ToTable(true, "date");
foreach (DataRow rows in tempdt1.Rows)
{
//找出原本資料表內每天的所有資料
DataRow[] rowitem = tempdt.Select(" date='" + rows["date"].ToString() + "' ");
double firstlat = 0, firstlng = 0, secondlat = 0, secondlng = 0;
double distance = 0;
//進行距離運算,下面語法不解釋了自己看吧
//GetDistance() 距離運算函式
foreach (DataRow rows1 in rowitem)
{
if (firstlat == 0 && firstlng == 0)
{
firstlat = double.Parse(rows1["y"].ToString());
firstlng = double.Parse(rows1["x"].ToString());
}
else if (secondlat == 0 && secondlng == 0)
{
secondlat = double.Parse(rows1["y"].ToString());
secondlng = double.Parse(rows1["x"].ToString());
distance += GetDistance(firstlat, firstlng, secondlat, secondlng);
}
else
{
firstlat = secondlat;
firstlng = secondlng;
secondlat = double.Parse(rows1["y"].ToString());
secondlng = double.Parse(rows1["x"].ToString());
distance += GetDistance(firstlat, firstlng, secondlat, secondlng);
}
}
//這裡可以輸出每天的里程,請自行運用
}


例2 : 資料庫撈出一群資料,我們需要似需求進行特定資料的累加(DataTable資料更新),每日筆數的累加,當然這是SQL語法可以直接達成的,沒有人會這們蠢的這樣使用,這裡只是舉例。
if (dt.Rows.Count > 0)
{
DataTable tempdt = new DataTable();
DataColumn temprow;
//定義資料欄位
temprow = new DataColumn();
temprow.DataType = System.Type.GetType("System.String");
temprow.ColumnName = "decive";
tempdt.Columns.Add(temprow);
temprow = new DataColumn();
temprow.DataType = System.Type.GetType("System.String");
temprow.ColumnName = "date";
tempdt.Columns.Add(temprow);
temprow = new DataColumn();
temprow.DataType = System.Type.GetType("System.Decimal");
temprow.ColumnName = "total";
tempdt.Columns.Add(temprow);
for (int i = 0; i < dt.Rows.Count; i++)
{
//找出當天的資料
DataRow[] rows = dt.Select(" date='" + dt.Rows[i]["date"].ToString() + "' ");
//如果日期存在累加計數器
if (rows.Length > 0)
{
rows[0]["total"] = decimal.Parse(rows[0]["total"].ToString()) + 1;
dt.ImportRow(rows[0]);
}
else
{
DataRow row = tempdt.NewRow();
row["decive"] = _deviceid;
row["date"] = dt.Rows[i]["date"].ToString();
row["total"] = 1;
tempdt.Rows.Add(row);
}
}
}

留言