How to combine two sum operations into one using LINQ?

I have this code

Dim sum As Integer = scores.Sum(Function(score) score.Fraction * score.Score) Dim count As Integer = scores.Sum(Function(score) score.Fraction) 

or in C #:

 var sum=scores.Sum(score=>score.Fraction * score.Score); var count=scores.Sum(score=>score.Fraction); 

How can I combine these AND AND achieve that the collection is only listed once? I found some examples, but if I'm not mistaken, they still repeat the collection twice.

+6
source share
2 answers
 var sum = 0; var count = 0; foreach(var score in scores){ sum += score.Fraction * score.Score; count += score.Fraction; } 

... I want to say why use LINQ at all - it simplified some things, but with LINQ it is not so simple.

+11
source

You can do this with Aggregate , although it hurts a bit, and creates an additional object for each iteration:

 var sums = scores.Aggregate(new { Sum = 0, Count = 0 }, (current, item) => new { Sum = current.Sum + item.Score * item.Fraction, Count = current.Count + item.Fraction }); 

Obviously, you could make this more efficient by creating a ValueTuple<T1, T2> structural tuple, but as a structure.

EDIT: I agree with Petar's point - if that is all you need to do, then LINQ will not really help in this situation.

+10
source

Source: https://habr.com/ru/post/897568/


All Articles