I inherited an application at work, and we're trying to allow a user to
select filter criteria and use that throughout the application, where
appropriate. That filter criteria comes back as a datatable with
non-unique records for a number of reasons that don't really matter right
now. For my purposes I have a DataTable, want to do the psuedo-equivalent
of data.SelectDistinct(ColumnName) and have that return a paired down version of
my DataTable for binding (it's a four column table and I want at least two
columns Name/Id for databinding).
I did some schoogling (err, googling) and found an implementation by Sahil here.
David Truxall
provided an alternate implementation
based on comments in the original thread that mentioned Hashtables.
David's implementation returned a DataTable with a single column, which wasn't
really what I wanted (see above) so I wrote up some tests, and finally got to
green with this:
public static DataTable SelectDistinct(DataTable sourceTable, string sourceColumn)
{
DataTable results = new DataTable();
foreach (DataColumn c in sourceTable.Columns)
{
results.Columns.Add(c.ColumnName, c.DataType);
}
try
{
Hashtable hashtable = new Hashtable();
foreach (DataRow row in sourceTable.Rows)
{
if (!hashtable.ContainsKey(row[sourceColumn]))
{
hashtable.Add(row[sourceColumn], null);
results.Rows.Add(row.ItemArray);
}
}
return results;
}
catch (System.Exception ex)
{
logError(ex, "SelectDistinct");
return null;
}
finally
{
results.Dispose();
}
}