Remove Duplicate rows records from DataTable c#


Overview: This article explains how to remove duplicate records from DataTable in C#. In SQL Server database if a table contains duplicate records then it is easy to select unique records by using DISTINCT built-in Ms-SQL function and get duplicate free rows. But when a Dot.NET c# DataTable contains duplicate records then, we have to do some extra work to get duplicate-free records in datatable.

In many blogs on similar articles, you find they use For loop, Dataview, Array List, and delete duplicate rows over looping, etc for removing duplicate rows.

Here I will show you a simple and much faster way, in this article, I create a function that gives unique records from a DataTable in C#.NET and returns a clean and duplicates-free record DataTable which will copy to new data table variable and get clean duplicate free distinct records.


On page load below written code will return distinct DataTable row records, i.e Remove duplicated rows.
protected void Page_Load(objectsender,EventArgse)
      DataTable getDistinctData = RemoveDuplicatesRecords(GetData());

private DataTable RemoveDuplicatesRecords(DataTable dt)
    //Returns just 5 unique rows
    DataTable dt2=UniqueRows.CopyToDataTable();
This is our DataBinding method
private static DataTable GetData()
	//Assume this returns all rows although there are just 5 distinct rows.
	SqlDataReader reader=null;
	DataTable dt=newDataTable();
	using(SqlConnection conn=newSqlConnection())
    	using(SqlCommand cmd=newSqlCommand())
        	cmd.CommandText="SELECT col1,col2 FROM tableName ORDER BY col1";
	return dt;
Yeah, we are done :)

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

Your email address will not be published. Required fields are marked *


  1. Zoheb 03/29/2013 12:11:16
    Sir I Salute you! :)
  2. satinder singh 03/30/2013 05:57:59
    You welcome :)
  3. Asava Samuel 04/03/2013 14:29:50

    Here is a database compatible with .NET, Silverlight, Windows Phone, Mono, Monodroid, and Monotouch:
  4. Anonymous 04/05/2013 05:56:02
    That is the simplest solution I have ever seen to this common situation. I'll be using this approach from now on. Nice one!
  5. Anonymous 04/08/2013 17:23:43
    my doubt is
    1 A
    2 B
    2 A

    result should be
    3 A
    2 B
  6. satinder singh 04/09/2013 11:45:53
    First of all in your above example their is no duplicate value, seem it has different ids( by looking at your first column), and also how you get result as 3 A" .

    Thanks for visiting and post comment (which improve my work) :)"
  7. satinder singh 04/09/2013 11:47:14
    My pleasure, if i helps anyone in anyway :)