李洋 2009年08月03日 星期一 13:34 | 2088次浏览 | 0条评论
The easiest way to get distinct DataRows in a DataTable or DataView is by using the DataView.ToTable() method.
原文地址:http://devpinoy.org/blogs/keithrull/archive/2008/02/07/how-to-get-the-distinct-rows-in-a-datatable-or-dataview.aspx
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)
Zeuux © 2024
京ICP备05028076号
暂时没有评论