How To: Get the DISTINCT rows in a DataTable or DataView#

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]  | 

 

Comments are closed.
All content © 2010, Keith Rull
On this page
This site
Calendar
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567
Archives
Sitemap
Blogroll OPML
Disclaimer

Powered by: newtelligence dasBlog 2.3.9074.18820

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

Send mail to the author(s) E-mail

Theme design by Jelle Druyts


Pick a theme: