Tuesday, September 25, 2007

Select Distinct columns from a DataTable

public static DataTable SelectDistinct(DataTable SourceTable, params string[] FieldNames)
{
object[] lastValues;
DataTable newTable;
DataRow[] orderedRows;
if (FieldNames == null FieldNames.Length == 0)
throw new ArgumentNullException("FieldNames");
lastValues = new object[FieldNames.Length];
newTable = new DataTable();
foreach (string fieldName in FieldNames)
newTable.Columns.Add(fieldName, SourceTable.Columns[fieldName].DataType);
orderedRows = SourceTable.Select("", string.Join(", ", FieldNames));
foreach (DataRow row in orderedRows)
{
if (!fieldValuesAreEqual(lastValues, row, FieldNames))
{
newTable.Rows.Add(createRowClone(row, newTable.NewRow(), FieldNames));
setLastValues(lastValues, row, FieldNames);
}
}
return newTable;
}

3 comments:

Ratheesh K R said...

It looks too good. This should really help me.

Ratheesh K R said...

OutStanding..........

Ratheesh K R said...
This comment has been removed by the author.