Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Linq to Sum by Index

Tags:

c#

.net

linq

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?

like image 822
Tarun Arora Avatar asked Jun 11 '13 17:06

Tarun Arora


2 Answers

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());
like image 199
Servy Avatar answered Nov 20 '22 15:11

Servy


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));
like image 4
Sergey Kalinichenko Avatar answered Nov 20 '22 15:11

Sergey Kalinichenko