使用LINQ总和由Index [英] Use Linq to Sum by Index

查看:118
本文介绍了使用LINQ总和由Index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有拥有96个值的集合。我想总结值4连续索引。我怎样才能做到这一点使用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?

示例

collection = {100, 101, 200, 150, 103, 105, 100, 104,  .........., 20, 40, 60, 80};



的总和(100,101,200,150;)然后总和(103,105,100,104;) ...那么(20,40,60,80 ;)这意味着现在我的新系列将有24个值。

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.

我怎样才能做到这一点使用LINQ?

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;
    }
}

在它的那样简单:

var query = data.Batch(4)
    .Select(batch => batch.Sum());

这篇关于使用LINQ总和由Index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆