How to Avoid Duplicate Rows In DataTable
Problem
One of the common problems faced in the data retrieval is to avoid duplicate rows from dataset or datatable. If you google for it, you will come across many solutions asking to loop through the complete in order to get rid of the duplicates. There is a very simple solution available in .Net that does not need looping but it comes with one problem that it can apply duplicate on a single column only.
Solution
For a dataset the following line will return distinct records for the column:
ds.Tables["MyTable"].DefaultView.ToTable(true,”column_name”);
For a datatable the following line of code will return distince records for the column:
dt.DefaultView.ToTable( true, “column_name”);
The first parameter of ToTable is a boolean for distinct or non-distinct. The second one is the name of the column. It is as simple as it looks
Recent Discussions