soniya soniya - 2 months ago 6
C# Question

select rows whose sum greater than 0 using Linq

I need to do, for example: Select customers whose total Sum of Amount is greater than 0. I tried below code and with reference to this result trying fetch data. but not getting Proper result.

var query = (from a in saleList
group a by a.Cust_Ledger_Entry_No into groups
select groups.Sum( s => s.Amount) > 0).ToList();


I did above query.Now I need data which satisfying above condition.Please help me.

Answer

You need a Where

var query = from a in saleList
            group a by a.Cust_Ledger_Entry_No into g
            where g.Sum( s => s.Amount) > 0
            select new { Cust_Ledger_Entry_No = g.Key, SumAmount = g.Sum( s => s.Amount) };

I need result like, customers whose sum of amount greater than 0 with all columns

If a is the customer and you need to select all you can use this query:

var query = from a in saleList
            group a by a.Cust_Ledger_Entry_No into g
            where g.Sum( s => s.Amount) > 0
            from customer in g  // flatten each group
            select customer;
Comments