I have a collection which has 96 values. I would like to sum values for 4 sequential indexes. How can I do this using Linq?
Example
collection = {100, 101, 200, 150, 103, 105, 100, 104, .........., 20, 40, 60, 80};
Sum of (100, 101, 200, 150;)
then sum of (103, 105, 100, 104;)
... then sum of (20, 40, 60, 80;)
This means now my new collection will have 24 values.
How can I do this using Linq?
We can start with this utility function to Batch
items up based on a given batch size:
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int batchSize)
{
List<T> buffer = new List<T>(batchSize);
foreach (T item in source)
{
buffer.Add(item);
if (buffer.Count >= batchSize)
{
yield return buffer;
buffer = new List<T>(batchSize);
}
}
if (buffer.Count > 0)
{
yield return buffer;
}
}
After that it's as simple as:
var query = data.Batch(4)
.Select(batch => batch.Sum());
You can group by index/4
to get your sums, like this:
var res = collection
.Select((v,i) => new {v, i})
.GroupBy(p => p.i / 4)
.Select(g => g.Sum(p.v));
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