SIGN UP MEMBER LOGIN:    
Blog

How to get Disticnt rows from a DataSet or Datatable?

Posted by Shyju Blogs | Current Affairs May 25, 2007
In many situation we need to avoid duplicate rows from data table. This will help to solve the issue.

How can I Retrieve distinct rows? -- How can I avoid duplicate rows from a DataTable?

One of the common issues in data layer is avoiding duplicate rows from dataset or datatable. I saw many people are writing separate function and looping through the datatable to avoid the duplicates. There is more simple ways available in .Net but people are unaware about this. I thought of writing a blog about this because I saw many blogs which mislead the people from right path. Thers is no need of looping or no need of logic are required to avoid the duplicates.

Following single line of code will avoid the duplicate rows.

ds.Tables["Employee"].DefaultView.ToTable(true,"employeeid");

ds - Dataset object

dt.DefaultView.ToTable( true, "employeeid");

dt - DataTable object

First option in ToTable is a boolean which indicates, you want distinct rows or not?

Second option in the ToTable is the column name based on which we have to select distinct rows.

Simple right, this option is the last one so most of the people didn't got the time to find it. Now your code will look much cleaner without those junk codes.

share this blog :
post comment
 

usefuf information thanks

Posted by Raj Kumar Dec 05, 2008

Hi, a very nice method, thanks a lot! But, is it possible to use functions to be "distincted", too, like SUM(Column). That's important for my Problem, but it doesn't work =/ I have a large DataSet with user specific columns and a value column and i want to get the the summarized values of each user. A "normal" SQL Statement would be easy: SELECT DISTINCT userColumn1, userColumn2, SUM(Value) FROM Table1. But with the Select Statement it doesn't work so =( Thx

Posted by Lupo Dec 04, 2008