Few random development Tips-N-Tricks-4

Remove duplicate rows from DataTable. Here’s a simple example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;

public partial class ComparingObject : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
    if (!IsPostBack)

private DataTable RemoveDuplicates(DataTable dt)
    //Returns just 10 unique rows
    var UniqueDataRows = dt.AsEnumerable().Distinct(DataRowComparer.Default);
    DataTable dt2 = UniqueDataRows.CopyToDataTable();
    return dt2;

private static DataTable GetData()
//This returns 182 rows although there are just 10 distinct rows.
SqlDataReader reader = null;
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection())
    conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnStr2"].ConnectionString;
    using (SqlCommand cmd = new SqlCommand())
        cmd.CommandText = "SELECT City, StateProvinceID " +
                          "FROM [AdventureWorks].[Person].[Address] where City like 'Sai%' ORDER BY City";
        cmd.Connection = conn;
        StringBuilder sb = new StringBuilder();
        reader = cmd.ExecuteReader();
return dt;


For more
That’s all about it. Thanks for reading.

This entry was posted in Tips-n-Tricks. Bookmark the permalink.

One Response to Few random development Tips-N-Tricks-4

  1. Roger Atkinson says:

    Hey that is a good post & a good set of coversations too. Keep sharing, that is good…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s