How To REMOVE DUPLICATE RECORDS FROM DATATABLE C# ASP.NET.
In SQL Server database if a table contain duplicate records then it is easy to select unique records by using DISTINCT function. But when a .NET DataTable contains duplicate records then, we have to do something extra work.
In many blogs on similar article you find they use For loop, Dataview, Array List and delete duplicated over looping etc etc for removing duplicates record.
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 DataTable
CODE:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RemoveDuplicatesRecords(GetData());
}
}
private DataTable RemoveDuplicatesRecords(DataTable dt)
{
//Returns just 5 unique rows
var UniqueRows = dt.AsEnumerable().Distinct(DataRowComparer.Default);
DataTable dt2 = UniqueRows.CopyToDataTable();
return dt2;
}
private static DataTable GetData()
{
//Assume this returns all rows although there are just 5 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 col1,col2 FROM tableName ORDER BY col1";
cmd.Connection = conn;
conn.Open();
reader = cmd.ExecuteReader();
dt.Load(reader);
conn.Close();
}
}
return dt;
}
Thank you for reading..
Không có nhận xét nào:
Đăng nhận xét