Adrift in .Net
I needed to perform a “Select Distinct“ on a datatable, not in the database, for binding to a listbox. Found a good solution here. Modified it according to one of the comments to use a hash table so sort order won't matter. Here is my version of the function:
private DataTable SelectDistinct(DataTable sourceTable, string sourceColumn){ DataTable result = null; try { result = new DataTable(); result.Columns.Add(sourceColumn, sourceTable.Columns[sourceColumn].DataType); Hashtable ht = new Hashtable(); foreach (DataRow dr in sourceTable.Rows) { if (!ht.ContainsKey(dr[sourceColumn])) { ht.Add(dr[sourceColumn], null); DataRow newRow = result.NewRow(); newRow[sourceColumn] = dr[sourceColumn]; result.Rows.Add(newRow); } } return result; } catch (System.Exception ex) { ExceptionManager.Publish(ex); return null; } finally { if (result != null) result.Dispose(); }}
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.