Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Select DISTINCT records based on specified fields for DataTable

4.95/5 (25 votes)
2 Feb 2011CPOL 200.8K  
Select DISTINCT records based on specified fields for DataTable
This will help you only when you have to filter distinct records based on specified fields.
e.g. I have a table called UserDetail which contains the following fields:

UserID | Name | Mobile | Email | City | State

Now I want to only display distinct records with Name, City and State, then you can use:

C#
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);

//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
   {
       DataTable dtUniqRecords = new DataTable();
       dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
       return dtUniqRecords;
   }


Thanks,
Imdadhusen

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)