今天遇到一個問題,需要分次從資料庫取出資料,接著把兩張資料表合併起來,我是個懶人,第一步當然就是先找找看有沒有方便的method可以快速使用啦~!
於是我使用Merge這個方法來完成這個小需求
果真方便快速^^!!
merage 這個method還有許多特殊的用法,這裡只提到最淺顯的合併表格而已
namespace DatatablePractice01
{
//練習將兩張資料表合起來
class Program
{
static void Main(string[] args)
{
DataTable dt1 = GetTable();
DataTable dt2 = GetTable();
//dt1.Rows.Add(.Rows);
dt1.Merge(dt2);
//印出資料
foreach (DataRow dr in dt1.Rows) {
Console.WriteLine("{0}\t{1}\t{2}\t{3}", dr["Weight"], dr["Name"], dr["Breed"], dr["Date"]);
}
Console.ReadLine();
}
static DataTable GetTable()
{
//
// Here we create a DataTable with four columns.
//
DataTable table = new DataTable();
table.Columns.Add("Weight", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Breed", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
//
// Here we add unsorted data to the DataTable and return.
//
table.Rows.Add(57, "Koko", "Shar Pei", DateTime.Now);
table.Rows.Add(130, "Fido", "Bullmastiff", DateTime.Now);
table.Rows.Add(92, "Alex", "Anatolian Shepherd Dog", DateTime.Now);
table.Rows.Add(25, "Charles", "Cavalier King Charles Spaniel", DateTime.Now);
table.Rows.Add(7, "Candy", "Yorkshire Terrier", DateTime.Now);
return table;
}
}
}
參考來源 : https://msdn.microsoft.com/zh-tw/library/fk68ew7b%28v=vs.110%29.aspx
文章標籤
全站熱搜
