May 16, 2011

How to get distinct rows from a DataTable

[DATATABLE].DefaultView.ToTable(true, FIELDS);

Very simple :)
Earlier to avoid duplicate values, I used a separate function which loop through the datatable to avoid the duplicates. But now it is not required

public static 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.Select("", fieldName))


if (lastValue == null

!(compareValues(lastValue, dr[fieldName])))


lastValue = dr[fieldName];

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



return dt;


No comments:

Post a Comment