top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

ASP.NET: Get Distinct records from datatable or dataset

+3 votes
359 views

By using DataTable DefaultView.ToTable() method we can get the distinct values of required columns of a datatable. the following 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"

image

 

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

image

 

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

image

 

posted Dec 1, 2015 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

...