The following code snippet shows you a way to extract distinct values in a specific column from a datatable.
// Datatable Creation
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Col1");
dt.Columns.Add(dc);
dc = new DataColumn("Col2");
dt.Columns.Add(dc);
DataRow dr = dt.NewRow();
dr[0] = "A1";
dr[1] = "B1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "A1";
dr[1] = "B2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "A1";
dr[1] = "B3";
dt.Rows.Add(dr);
// To Copy distinct values from col1 to a different datatable
DataTable uniqueCols = dt.DefaultView.ToTable(true, "col1");
We have got disctinct values of col1 into uniqueColTable. DefaultView.Totable can accept more than one column. The first parameter indicates that the method should fecth disinct values. you can also write dt.DefaultView.ToTable(true, “col1″,”col2”); which will fecth distinct values from both the column combination and copy that to new datatable.
Print | posted on Tuesday, March 29, 2011 9:17 AM