Get sum from a DataColumn values in C#

hamze picture hamze · Oct 10, 2011 · Viewed 7.5k times · Source

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#?

Answer

Anas Karkoukli picture Anas Karkoukli · Oct 10, 2011

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.