Monday, February 05, 2007

Select Distinct form Datatable

 

I need to write a code by which I can show distinct product name in drop down list and I have to do that from code once I have received dataset from DAL. I can iterate through all records and sore the distinct values in Array. I thought some other way for this. My function will take datatable as argument and returns new datatable with only one colun on which yu want distinct records. You may change it and return all the columns just by changing few lines. Below is the function,

 

private DataTable SelectDistinct(string ReturnTableName, DataTable SourceTable, string ReturnFieldName, string AdditionalFilterExpression)
{
DataTable dt = new DataTable(ReturnTableName);
dt.Columns.Add(ReturnFieldName, SourceTable.Columns[ReturnFieldName].DataType);
object LastValue = null;
foreach (DataRow dr in SourceTable.Select("", ReturnFieldName + " Asc"))
{
if (LastValue == null || !(ColumnEqual(LastValue, dr[ReturnFieldName])))
{
LastValue = dr[ReturnFieldName];
dt.Rows.Add(new object[] { LastValue });
}
}

return dt;
}

//Following function compares the value of two objects and returns true or false based on the same.
private bool ColumnEqual(object A, object B)
{
// Compares two values to see if they are equal. Also compares DBNULL.Value.
// Note: If your DataTable contains object fields, then you must extend this
// function to handle them in a meaningful way if you intend to group on them.

if (A == DBNull.Value && B == DBNull.Value) // both are DBNull.Value
return true;
if (A == DBNull.Value || B == DBNull.Value) // only one is DBNull.Value
return false;
return (A.Equals(B)); // value type standard comparison
}

Happy Programing.

No comments: