May 16, 2011

How to get distinct rows from a DataTable

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

Very simple :) http://msdn.microsoft.com/en-us/library/h2b6ehaa.aspx
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;

}
 
http://www.codeproject.com/KB/database/SelectDistinctCSharp.aspx

No comments:

Post a Comment