top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to get Distinct records from datatable or dataset?

+2 votes
372 views
How to get Distinct records from datatable or dataset?
posted Feb 1, 2016 by Latha

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

By using DataTable DefaultView.ToTable() method we can get the distinct values of required columns of a datatable. the follwing example will explain how to do that.

  DataTable dt = new DataTable("ResultSet");
    dt.Columns.Add("Country");
    dt.Columns.Add("State");
    dt.Columns.Add("Place");
    dt.Rows.Add("India", "Andhrapradesh", "Charminar");
    dt.Rows.Add("India", "Andhrapradesh", "Steel Plant");
    dt.Rows.Add("India", "Maharastra", "IT Hub");
    dt.Rows.Add("India", "Tamilnadu", "Beach House");
    dt.Rows.Add("India", "Tamilnadu", "Club House");
    dt.Rows.Add("USA", "Dallas", "Airport");
    dt.Rows.Add("Australia", "Sydney", "Stadium");
    DataTable dtCountry = dt.DefaultView.ToTable("Countries", true, "Country");
    DataTable dttemp = dt.DefaultView.ToTable("Temp", true, "Country", "State");

In the above example dtCountry will contain the distinct Countries and dttemp will contain the distinct Countries and States.

Output of "dt"

enter image description here

Output of DataTable dtCountry = dt.DefaultView.ToTable("Countries", true, "Country");

enter image description here

Output of DataTable dttemp = dt.DefaultView.ToTable("Temp", true, "Country", "State");

enter image description here

answer Feb 1, 2016 by Shivaranjini
...