Archive for May, 2005

Select Distinct in a DataTable (The Whidbey Version)

In my last post I described a “Select Distinct“ function for a datatable. This is a whole lot easier using Whidbey. You can get a distinct table based on a column in the DefaultView of the datatable:

DataTable d = dataSetName.dataTableName.DefaultView.ToTable(true, new string[] { "ColumnName" });

Posted on:
Posted in .Net 2.0, ADO.Net | Comments Off on Select Distinct in a DataTable (The Whidbey Version)

Select Distinct in a DataTable

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();
    }
}

Posted on:
Posted in ADO.Net | Comments Off on Select Distinct in a DataTable