none
sum in linq RRS feed

  • Question

  • Hi

    i have this sqlQuary

    Select sum(pay) as totalPay from tblSalary

    WHERE customerID = @customerID

    how can i change it to linq

    thanks

    • Moved by Jie Bao Monday, June 28, 2010 1:46 AM Linq (From:Windows Presentation Foundation (WPF))
    Sunday, June 27, 2010 4:17 PM

Answers

  •  var t =(from r in db.tblDebtPays

                where r.MemberID == 1 select r).Sum();

     

    Here you cannot use just use "select r", a small change in my previouse update.

    var k = (from Row r in tblSalary where r.customerID = xyz select r.pay).Sum();
    

    it is "r.pay" and not "pay". provided r.pay should give a decimal value.


    - Jegan
    • Proposed as answer by KristoferAEditor Monday, June 28, 2010 6:15 AM
    • Marked as answer by H.Aftabi Friday, July 2, 2010 1:11 PM
    Monday, June 28, 2010 4:04 AM

All replies

  • var k = (from Row r in tblSalary where r.customerID = xyz select pay).Sum();

    here assume that tblSalary is collection of Row, and Row has a property named customerID


    - Jegan
    Sunday, June 27, 2010 5:06 PM
  • thank 

    i chang to

     var t =(from r in db.tblDebtPays
                where r.MemberID == 1
                select r).Sum();

    but get this error

    Error	1	'System.Linq.IQueryable<CashDAL.tblDebtPay>' does not contain a definition for 'Sum' and the best extension method overload 'System.Linq.ParallelEnumerable.Sum(System.Linq.ParallelQuery<decimal?>)' has some invalid arguments	D:\New Win Project\Cash\Cash\PayDebt.xaml.cs	66	34	Cash
    

    Sunday, June 27, 2010 5:55 PM
  • You can't make a sum of the entire row ...select r).Sum... Change the select to retrieve the column you want to sum up:

    var t =(from r in db.tblDebtPays
                where r.MemberID == 1
                select r.pay).Sum();

    ...or...

    var t = db.tblDebtPays.Where(r => r.MemberID == 1).Sum(p => r.Pay);


    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework:
    huagati.com/dbmltools (add-in with new features for the L2S and EF designers in VS2008 and VS2010)
    huagati.com/L2SProfiler (Query profiler for Linq-to-SQL and LLBLGen Pro)
    Monday, June 28, 2010 2:18 AM
    Answerer
  •  var t =(from r in db.tblDebtPays

                where r.MemberID == 1 select r).Sum();

     

    Here you cannot use just use "select r", a small change in my previouse update.

    var k = (from Row r in tblSalary where r.customerID = xyz select r.pay).Sum();
    

    it is "r.pay" and not "pay". provided r.pay should give a decimal value.


    - Jegan
    • Proposed as answer by KristoferAEditor Monday, June 28, 2010 6:15 AM
    • Marked as answer by H.Aftabi Friday, July 2, 2010 1:11 PM
    Monday, June 28, 2010 4:04 AM