In many blogs on similar article, 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 which gives unique records from a DataTable in C#.NET and return a clean and duplicate free record DataTable which will copy to new datatable variable and get clean duplicate free distinct records.
Code-Behind:
On page load below written code will return distinct DataTable row records, i.e Remove duplicated rows.
//*
protected void Page_Load(objectsender,EventArgse)
{
if(!IsPostBack)
{
DataTable getDistinctData = RemoveDuplicatesRecords(GetData());
}
}
private DataTable RemoveDuplicatesRecords(DataTable dt)
{
//Returns just 5 unique rows
varUniqueRows=dt.AsEnumerable().Distinct(DataRowComparer.Default);
DataTable dt2=UniqueRows.CopyToDataTable();
returndt2;
}
//*
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())
{
conn.ConnectionString=ConfigurationManager.ConnectionStrings["ConnStr2"].ConnectionString;
using(SqlCommand cmd=newSqlCommand())
{
cmd.CommandText="SELECT col1,col2 FROM tableName ORDER BY col1";
cmd.Connection=conn;
conn.Open();
reader=cmd.ExecuteReader();
dt.Load(reader);
conn.Close();
}
}
return dt;
}
//*
Yeah, we are done π
Hope you enjoyed this tutorial. If you have any recommendations, please let us know what you think in the comment section below! See you again next time!
11 comments on βRemove Duplicate rows records from DataTable Asp.net c#β
Thank You .it is very helpful
Hi Pallab,
Thanks for reading.
this is very slow in speed .
On which basis you came to know its slow? Pls provide me some test cases, so i can overcome with this, also if you have any aternative best way to do then do share with me π
That is the simplest solution I have ever seen to this common situation. I’ll be using this approach from now on. Nice one!
My pleasure, if i helps anyone in anyway π
Zoleb
Here is a database compatible with .NET, Silverlight, Windows Phone, Mono, Monodroid, and Monotouch:
http://www.kellermansoftware.com/p-43-ninja-net-database-pro.aspx
Sir I Salute you! π
You welcome π
my doubt is
1 A
2 B
2 A
result should be
3 A
2 B
Hi
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) π