First, of all you need to download MoreLinq Library and import in your project. After Implement `morelinq` you can use a function called `DistinctBy` in which you can specify the property on which you want to find Distinct objects.
Duplicate free Datatable using more-linq ( morelinq )
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 want. i.e. distinct value by ID column
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();
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!