Populate a DataTable (with Aggregation) from an existing DataTable

G

Guest

Hi,

I have a datatable with 2 keys columns, i need get this datatable with agregate totals.

How can i do that?

datatable
Key1 Key2 Total
1 1 100
1 1 200
1 2 50
1 2 10
2 1 100


i need other dattable agregate totals
key1 key2 Total
1 1 300
1 2 60
2 1 100
 
M

Mohamoss

Hi
I don't think there is an easy way to do it but here is a way that might
help get your job done.
First you will loop throw all the table, pick a row , find all the tows
that share the same keys as this row . once you find such a row you will
delete it and add its total to the row that you are looping on.

for( int idx = 0; idx < r.Count; idx++ )
{
DataRow row = mytable.Rows[ idx ];//this is the row that we will be
//comparing to the rest of the table
for( int inside = idx; inside < r.Count; inside++ )
{


DataRow comparedRow = mytable.Rows[ inside ];//get rows to compare with
//"row"

If(( row[ key1].ToString() == comparedRow[ key1].ToString())&&( row[
key2].ToString() == comparedRow[ key2].ToString())) // so they both share
key means we should delete //compared row
{
// *add the total of comparedRow to the total of row first*
r.RemoveAt( inside );//then remove compared row
inside--;
}
}
}








The deleted rows will be only marked as deleted so you either upadate
dataset with the AcceptChanges method

Or remove them completely

for( int idx = 0; idx < r.Count; idx++ )
{

DataRow row = mytable.Rows[ idx ];
if( row.RowState == DataRowState.Deleted )
{

r.RemoveAt( idx );
idx--;
}
}
How this helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top