Saturday, April 12, 2008

How to get distinct rows from a datatable in ASP.Net

If you want to get distinct rows from a datatable you can write this three lines of code andyou are done with it

DataTable dt = ds.Tables[2];

DataView dv = dt.DefaultView;

// true for getting distinct rows

dt=dv.ToTable(true, “ColumnName”);

or you can use this two functions

//Calling from some function

dt = SelectDistinct(dt, "coloumName");

///////////////////////

public DataTable SelectDistinct( DataTable SourceTable, string FieldName)

{

DataTable dt = new DataTable();

dt.Columns.Add(FieldName, SourceTable.Columns[FieldName].DataType);

object LastValue = null;

foreach (DataRow dr in SourceTable.Rows)

{

if (LastValue == null || !(ColumnEqual(LastValue, dr[FieldName])))

{

LastValue = dr[FieldName];

dt.Rows.Add(new object[] { LastValue });

}

}

return dt;

}

private bool ColumnEqual(object A, object B)

{

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

}

No comments: