views:

44

answers:

3

select sum(Sales) from WeeklyProductSale. how i can write this query in linq and what this query will return to me.

thankas in advance.

A: 
var answer = db.WeeklyProductSales.Sum (s => s.Sales);

This will return a variable of type s.Sales (e.g., decimal).

Edit: if you querying a DataTable, you will need to do this:

myDataTable.AsEnumerable().Sum (row => (decimal) row["Sales"]).

Make sure you reference System.Data.DataSetExtensions.dll and put "using System.Data.DataSetExtensions" into your program because the AsEnumerable extension method that this query uses relies on this. Change (decimal) to the type of the Sales column.

Joe Albahari
i am getting the data in to data table.so can i create linq query on data table.
gofor.net
A: 

VB.Net

Dim sumOfSales = Aggregate wps In db.WeeklyProductSale Into Sum(wps.Sales)
barrylloyd
A: 

You can write it like this,

YourDBContextObject.WeeklyProductSales.Sum(w => w.Sales);
A_Nablsi
It will only return decimal if the type of Sales is decimal too!
Olli
Thanks for the correction, you are write the function has 20 override and the return value depends on the type of the Sales.
A_Nablsi