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
  1. #region DATASET HELPER
  2. private bool ColumnEqual(object A, object B) {
  3. // Compares two values to see if they are equal. Also compares DBNULL.Value.
  4. if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
  5. return true;
  6. if (A == DBNull.Value || B == DBNull.Value) // only one is BNull.Value
  7. return false;
  8. return (A.Equals(B)); // value type standard comparison
  9. }
  10. public DataTable SelectDistinct(DataTable SourceTable, string FieldName) {
  11. // Create a Datatable – datatype same as FieldName
  12. DataTable dt = new DataTable(SourceTable.TableName);
  13. dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);
  14. // Loop each row & compare each value with one another
  15. // Add it to datatable if the values are mismatch
  16. object LastValue = null;
  17. foreach(DataRow dr in SourceTable.Select("", FieldName)) {
  18. if (LastValue == null || !(ColumnEqual(LastValue, dr[FieldName]))) {
  19. LastValue = dr[FieldName];
  20. dt.Rows.Add(new object[] { LastValue });
  21. }
  22. }
  23. return dt;
  24. }
  25. #endregion
Example
Consider the following Dataset dsOrders,
1.gif
Get distinct Product from this Dataset,
  1. DataTable distinctDT = SelectDistinct(dsOrders.Tables[0], "Product");
For CashMode,
  1. DataTable distinctDT = SelectDistinct(dsOrders.Tables[0], "CashMode");
Output
2.gif