Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
 Thursday, February 07, 2008

Here's a small trick i use alot.

QuestionWhat's the easiest way to get the distict rows of data in a DataTable and DataView in .NET 2.0?

AnswerThe easiest way to get distinct DataRows in a DataTable or DataView is by using the DataView.ToTable() method.

Now lets demonstrate. Assuming that I have this table of data in a DataTable:

and I want to get the the DISTINCT Account Numbers and Account Name from that DataTable. What I need to do is to create a DataView object out of my DataTable.

//A sample service layer. neglect!
AccountPositionService service = new AccountPositionService();
//lets get the positions
DataTable positionsTable = service.GetPositions();
//create our view
DataView positionView = positionsTable.DefaultView;

Then call the DataView.ToTable() method:

//Create a new DataTable called Accounts with the columns 
//AccountNumber and AccountName then Populate it with DISTINCT rows of data.
DataTable accountsTable = positionView.ToTable("Accounts", true, "AccountNumber", "AccountName");

The result of the method call would be:

What happend in the method above is that the DataView.ToTable() method accepted three parameters. The first parameter is for the DataTable name which in our case is called "Accounts". The second parameter is use to specify whether the values to be populated to the new DataTable is distinct. The third parameter which is a param[] string specifies the columns to be created on the DataTable which in our case are "AccountNumber" and "AccountName". This columns are also the basis used to create the distinct comparisson. Pretty cool huh?

Download the source code here: KeithRull.HavingFunWithDataTables.zip (3.56 KB)

Thursday, February 07, 2008 9:06:10 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET
Archive
<February 2008>
SunMonTueWedThuFriSat
272829303112
3456789
10111213141516
17181920212223
2425262728291
2345678
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2008
Keith Rull
Sign In
Statistics
Total Posts: 260
This Year: 57
This Month: 0
This Week: 0
Comments: 116
Themes
Pick a theme:
Ads
All Content © 2008, Keith Rull
DasBlog theme 'Business' created by Christoph De Baene (delarou)