Menu ▼



Posted By :
avatarmrkraju
Total Views : 5934

Get Distinct records from datatable or dataset

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"



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



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







comments powered by Disqus


Search dotnetlearners.com