ARTICLE

How to: Select distinct values from Dataset

Posted by anand palanichamy Articles | ADO.NET in C# June 07, 2010
In this article you will see how to get the distinct values from the Dataset.
Reader Level:

Dataset is a most powerful and easy-to-use component of ADO.Net. In this section you will see how to get the distinct values from the Dataset.

CODE:

#region DATASET HELPER
private bool ColumnEqual(object A, object B)
{
    // Compares two values to see if they are equal. Also compares DBNULL.Value.           
    if (A == DBNull.Value && B == DBNull.Value) //  both are DBNull.Value
            return true;
    if (A == DBNull.Value || B == DBNull.Value) //  only one is BNull.Value
            return false;
    return (A.Equals(B));  // value type standard comparison
}
public DataTable SelectDistinct(DataTable SourceTable, string FieldName)
{
    // Create a Datatable – datatype same as FieldName
    DataTable dt = new DataTable(SourceTable.TableName);
    dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);
    // Loop each row & compare each value with one another
    // Add it to datatable if the values are mismatch
    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,

1.gif

Get distinct Product from this Dataset, 

DataTable distinctDT = SelectDistinct(dsOrders.Tables[0], "Product");

For CashMode,

DataTable distinctDT = SelectDistinct(dsOrders.Tables[0], "CashMode");

Output:

2.gif

Login to add your contents and source code to this article
post comment
     

You can select distinct from dataset as datatable dt= dsOrders.Tables[0]..DefaultView.ToTable(True, "ColumnName")

Posted by pooja shete Jun 28, 2011

Goode one

Posted by sunil t Jun 07, 2010
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts