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


Remove duplicate row from Database with moreLinq: Here in this article, I am going to show you how to remove duplicate records from datatable depending upon specific Column-Name. I recommend you to check my previous article (CLICK) where has written how to remove the 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 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 records which actually we want. 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();

Conclusion: Here using moreLinq we can able to remove duplicate rows from our data table by providing column names that we want to distinct.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

Post Comment

Your email address will not be published. Required fields are marked *