第一種,使用Linq查詢表達式,code如下
DataTable testtable = new DataTable(); testtable.Columns.Add("ID"); testtable.Columns.Add("ProductName"); testtable.Rows.Add("1", "1"); testtable.Rows.Add("1", "1"); testtable.Rows.Add("1", "1"); testtable.Rows.Add("2", "2"); testtable.Rows.Add("3", "3"); DataTable finalltable = new DataTable(); finalltable = testtable.Clone(); finalltable.Clear(); var rows = from row in testtable.AsEnumerable() group row by row["ID"] into myrow select myrow.FirstOrDefault(); foreach (DataRow row in rows) { finalltable.ImportRow(row); }
第二種方法
利用dataview來過濾datatable
testtable = testtable.DefaultView.ToTable(true, new string[] { "ID", "ProductName" });