Dataset is the most powerful and easy-to-use component of ADO.Net. In this section, you will see how to get distinct values from the Dataset.
CODE
- #region DATASET HELPER
- private bool ColumnEqual(object A, object B) {
-
- if (A == DBNull.Value && B == DBNull.Value)
- return true;
- if (A == DBNull.Value || B == DBNull.Value)
- return false;
- return (A.Equals(B));
- }
- public DataTable SelectDistinct(DataTable SourceTable, string FieldName) {
-
- DataTable dt = new DataTable(SourceTable.TableName);
- dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);
-
-
- object LastValue = null;
- foreach(DataRow dr in SourceTable.Select("", FieldName)) {
- if (LastValue == null || !(ColumnEqual(LastValue, dr[FieldName]))) {
- LastValue = dr[FieldName];
- dt.Rows.Add(new object[] { LastValue });
- }
- }
- return dt;
- }
- #endregion
Example
Consider the following Dataset dsOrders,
Get distinct Product from this Dataset,
- DataTable distinctDT = SelectDistinct(dsOrders.Tables[0], "Product");
For CashMode,
- DataTable distinctDT = SelectDistinct(dsOrders.Tables[0], "CashMode");
Output