Let's say I have the following data in a database.
class Data
{
public int Category { get; set; }
public int ValueA { get; set; }
public int ValueB { get; set; }
}
How can I write a LINQ query to get the sum of ValueA
and also the sum of ValueB
for all rows with Category == 1
?
I know I could load all the data and then use Sum
on the loaded data but would prefer to total them in the database.
I know I can use group by
but I'm not grouping by anything. I just want these two totals from the data.
Items select new { Sum(p. Total), Sum(p. Done)};
In LINQ, you can find the sum of the given numeric elements by using the Sum() method. This method calculates the sum of the numeric value present in the given sequence. It does not support query syntax in C#, but it supports in VB.NET. It is available in both Enumerable and Queryable classes in C#.
Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one.
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
LINQ query expression to get sum of numbers which match specified predicate. var list = new List < int > { 8, 2, 6, 3 }; int sum = ( from x in list where x > 4 select x). Sum (); LINQ query expression to get sum of string lengths using selector.
If you REALLY want to use LINQ you could use var results = from x in MyDataList select new { TextColumn = x.TextColumn, NumberColumn0 = x.NumberColumn0, NumberColumn1 = x.NumberColumn1, Total = x.NumberColumn1 + x.NumberColumn0};
This way you have no need for LINQ. If you REALLY want to use LINQ you could use var results = from x in MyDataList select new { TextColumn = x.TextColumn, NumberColumn0 = x.NumberColumn0, NumberColumn1 = x.NumberColumn1, Total = x.NumberColumn1 + x.NumberColumn0};
LINQ query expression to get sum of numbers which match specified predicate. var list = new List < int > { 8, 2, 6, 3 }; int sum = ( from x in list where x > 4 select x).
If you are using EF, you can try this:
var result= context.Data.Where(d=>d.Category == 1)
.GroupBy(d=>d.Category)
.Select(g=>new {
SumA=g.Sum(d=>d.ValueA),
SumB=g.Sum(d=>d.ValueB)
}
);
You can group by a constant
var result = from d in context.Data
where d.Category == 1
group d by 1 into g
select
{
ASum = g.Sum(d => d.ValueA),
BSum = g.Sum(d => d.ValueB)
};
Or as octavioccl pointed out you can also group by Category
since it will be a constant value because of the where
clause. But using a constant is how you can achieve what you want in the general case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With