1.Distinct
a.get datatable
IEnumerable<DataRow> query = (from c in contact.AsEnumerable()
select c).Take(100);
DataTable contactsTableWith100Rows = query.CopyToDataTable();
b.use Distinct operator
List<DataRow> rows = new List<DataRow>();
//加入重覆的 datarows 資料
foreach (DataRow row in contactsTableWith100Rows.Rows)
rows.Add(row);
// Create duplicate rows by adding the same 100 rows to the list.
foreach (DataRow row in contactsTableWith100Rows.Rows)
rows.Add(row);
DataTable table =
System.Data.DataTableExtensions.CopyToDataTable<DataRow>(rows);
IEnumerable<DataRow> uniqueContacts =
table.AsEnumerable().Distinct(DataRowComparer.Default);
2.Except
傳回在第一份資料表中出現但沒有在第二份資料表中出現的連絡人
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds); //the function set dataadpter to dataset
DataTable contactTable = ds.Tables["Contact"];
// Create two tables.
IEnumerable<DataRow> query1 = from contact in contactTable.AsEnumerable()
where contact.Field<string>("Title") == "Ms."
select contact;
IEnumerable<DataRow> query2 = from contact in contactTable.AsEnumerable()
where contact.Field<string>("FirstName") == "Sandra"
select contact;
DataTable contacts1 = query1.CopyToDataTable();
DataTable contacts2 = query2.CopyToDataTable();
// Find the contacts that are in the first
// table but not the second.
var contacts = contacts1.AsEnumerable().Except(contacts2.AsEnumerable(),
DataRowComparer.Default);
3.Intersect
傳回在這兩份資料表中都出現的連絡人
IEnumerable<DataRow> query1 = from contact in contactTable.AsEnumerable()
where contact.Field<string>("Title") == "Ms."
select contact;
IEnumerable<DataRow> query2 = from contact in contactTable.AsEnumerable()
where contact.Field<string>("FirstName") == "Sandra"
select contact;
DataTable contacts1 = query1.CopyToDataTable();
DataTable contacts2 = query2.CopyToDataTable();
// Find the intersection of the two tables.
var contacts = contacts1.AsEnumerable().Intersect(contacts2.AsEnumerable(),
DataRowComparer.Default);
4.Union
傳回在其中一份資料表中出現的唯一連絡人
DataTable contactTable = ds.Tables["Contact"];
IEnumerable<DataRow> query1 = from contact in contactTable.AsEnumerable()
where contact.Field<string>("Title") == "Ms."
select contact;
IEnumerable<DataRow> query2 = from contact in contactTable.AsEnumerable()
where contact.Field<string>("FirstName") == "Sandra"
select contact;
DataTable contacts1 = query1.CopyToDataTable();
DataTable contacts2 = query2.CopyToDataTable();
// Find the union of the two tables.
var contacts = contacts1.AsEnumerable().Union(contacts2.AsEnumerable(),
DataRowComparer.Default);