David Truxall

Adrift in .Net

<October 2008>
SuMoTuWeThFrSa
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678


Navigation

Other Good Blogs

My Other Articles on CodeProject

Subscriptions

News

Day of .Net October 18, 2008 - Be there!
View David Truxall's profile on LinkedIn
My presentations on SlideShare

Post Categories



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 Wednesday, May 25, 2005 11:26 AM by davetrux





Powered by Dot Net Junkies, by Telligent Systems