Sponsors

Thứ Tư, 10 tháng 4, 2013

moreLinq DistinctBy - How To Remove Duplicate Record From DataTable Based On Specific ColumnName

Using moreLinq DistinctBy method to remove duplicate records

Here in this article i am going to show you how to remove duplicate record from datatable depending upon specific 
ColumnName . I recommend you to check my previous article (CLICK) where have written how to remove duplicate record from DataTable without use For loop, Dataview, Array List and delete duplicated over looping etc and delete.

First of all you need to add MoreLinq Library in your project  . After Implement morelinq you can use function called DistinctBy in which you can specify the property on which you want to find Distinct objects.

CODE:
 protected void Page_Load(object sender, EventArgs e)
{
// Distinctby column name ID
var valueDistinctByIdColumn = getDT().AsEnumerable().DistinctBy(row => new { Id = row["Id"] });
DataTable dtDistinctByIdColumn = valueDistinctByIdColumn.CopyToDataTable();
}

public DataTable getDT()
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add("1", "sunny");
dt.Rows.Add("2", "vicky");
dt.Rows.Add("3", "prince");
dt.Rows.Add("2", "john");
dt.Rows.Add("5", "sunny");
dt.Rows.Add("1", "sunny");
return dt;
}
OUTPUT:
DistinctBy Column ID:
Here  you can see in output there is only four record which actually we wants. i.e. distinct value by ID column


 Display all records
If you want to do distinct by 2nd column ie(Name)


var valueDistinctByNameColumn = getDT().AsEnumerable().DistinctBy(row => new { Name = row["Name"] });
DataTable dtDistinctByNameColumn = valueDistinctByNameColumn.CopyToDataTable();
Thank you for reading..



Không có nhận xét nào:

Đăng nhận xét