Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Select DISTINCT records based on specified field from DataTable

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.13k
    Comment on it

    This blog will help you when you need to select distinct records from a datatable on basis of selected columns.

    Suppose we have a datatable which holds the employee records. This datatable has following columns

    1. Name
    2. FatherName
    3. City
    4. Qualification

    We have multiple rows in the datatable and we have a task to show only distinct records for columns Name, FatherName and City. i.e don`t include Qualification as the criteria for distinct record selection but keep the column in resultant datatable along with the distinct criteria columns.


    In c# this can be done with the help of DataView. Here is the sample code

    string[] distinctColumnNames = {"Name","FatherName","City"};
    DataTable dtUniqueEmployees = GetDistinctEmployees(dtWithDuplicate, distinctColumnNames );
    //Following function will return Distinct records for Name, FatherName and City column.
    public static DataTable GetDistinctEmployees(DataTable dtWithDuplicate, string[] distinctColumnNames)
           DataTable dtUniqueEmployees = new DataTable();
           dtUniqueEmployees = dtWithDuplicate.DefaultView.ToTable(true, distinctColumnNames );
           return dtUniqueEmployees ;

    In above example, we have a datatable dtWithDuplicate which has mixed records for columns Employees, Fathername , and City. we want to select only the distinct records. So in first line we are creating the array of distinct column names. In the next line we are calling the method GetDistinctEmployees and passing the parameters dtWithDuplicate and distinctColumnNames to that method.


    In the body of the method, we are creating a new  dtUniqueEmployees object of datatable. In the next line we use DefaultView.ToTable method of Datatable and passing the distinct column name array to it. This will filter the distinct record and return only those rows which have distinct values for column names Name, FatherName and city.


 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: