Get sum from a DataColumn values in C#

那年仲夏 提交于 2021-02-10 14:23:56

问题


I have a table in a dataadapter. I want to get the count and sum of a specific column of it. How is that possible?

  • This is the code for reach to the column, what after that?

    DataColumn buy_count = myDataSet.Tables["all_saled"].Columns["how_much_buy"]

I know that we have sum, count,... in SQL, but how can I do it in C#?


回答1:


You can use LINQ to DataSets

var sales = myDataSet.Tables["all_saled"].AsEnumerable();

var buy_total = sales.Sum(datarow => datarow.Field<int>("how_much_buy")); 

Check the LINQ to DataSets 101 Samples

P.S. might need the System.Data.DataSetExtensions assembly referenced.




回答2:


Use the DataTable.Compute method:

int total = (int)myDataSet.Tables["all_saled"].Compute("SUM(how_much_buy)", null);


来源:https://stackoverflow.com/questions/7707290/get-sum-from-a-datacolumn-values-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!