hi in this post i will show to find duplicate records in a datatable or dataset using LINQ.
Example:
Below is the sample employee table which i will take it into a datatable and then will search for duplicate employee names present inside the table using a LINQ query.
Code :
public void checkDuplicate()
{
string conStr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString.ToString();
StringBuilder s = new StringBuilder();
SqlConnection s1 = new SqlConnection(conStr);
s1.Open();
string queryString = "SELECT * FROM employee";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, s1);
DataSet employee = new DataSet();
adapter.Fill(employee, "employee");
var duplicateRecords = employee.Tables[0].AsEnumerable()
.GroupBy(r => r["EmpName"]) //coloumn name which has the duplicate values
.Where(gr => gr.Count() > 1)
.Select(g => g.Key);
foreach (var d in duplicateRecords)
{
s.Append("," + d.ToString());
}
Response.Write("<script language='javascript'>alert('Duplicates Names: "+ s.ToString() +"');</script>");
s1.Close();
}
Output :
Example:
Below is the sample employee table which i will take it into a datatable and then will search for duplicate employee names present inside the table using a LINQ query.
1. EMP Table |
Code :
public void checkDuplicate()
{
string conStr = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString.ToString();
StringBuilder s = new StringBuilder();
SqlConnection s1 = new SqlConnection(conStr);
s1.Open();
string queryString = "SELECT * FROM employee";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, s1);
DataSet employee = new DataSet();
adapter.Fill(employee, "employee");
var duplicateRecords = employee.Tables[0].AsEnumerable()
.GroupBy(r => r["EmpName"]) //coloumn name which has the duplicate values
.Where(gr => gr.Count() > 1)
.Select(g => g.Key);
foreach (var d in duplicateRecords)
{
s.Append("," + d.ToString());
}
Response.Write("<script language='javascript'>alert('Duplicates Names: "+ s.ToString() +"');</script>");
s1.Close();
}
Output :
Output |
No comments:
Post a Comment