简体   繁体   中英

Group by in dataset and update the same dataset

I have a dataset like -

  Currency        amount

    USD         1245
    INR         564
    USD         45645
    INR         5676
    JPY         5677

I want to group by Currency and aggregate the amount as well and update the same dataset.

The final dataset should be like -

Currency     Amount  
USD           46890
INR           6240
JPY           5677

You can use Linq-To-DataTable and Enumerable.GroupBy :

var grouped = table.AsEnumerable()
                   .GroupBy(r => f.Field<String>("Currency"))
                   .Select( g => new  { 
                            Currency = g.Key, 
                            Amount = g.Sum(r => r.Field<int>("amount")) 
                   });

var table2 = table.Clone(); // you can also just use the original table, i just didn't want to merge the data here
foreach(var grp in grouped)
{
    var newRow = table2.Rows.Add();
    newRow.SetField("Currency") = grp.Currency;
    newRow.SetField("amount") = grp.Amount;
}

Now you can use a DataAdapter to update the database from the DataTable .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM