Linq以四元组的形式获取数据 [英] Linq get data as quaternary packs

查看:101
本文介绍了Linq以四元组的形式获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢将所有数据选择为不可预测数量的四元包装(每个包装包含四个项目),例如:

I like to select all data as unpredictable number of quaternary packages (packs which each contains four item) something like the fallowing:

foreach(var quaternary in myEnauerable.ToQuaternaryPackages())
{
    //Whatever (Like: l=page.Add(new List()))
    foreach(var item in quaternary)
    {
        //Whatever (Like: l.Add(item))
    }
}

推荐答案

使用linq非常简单:

it's quite simple using linq:

public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int batchSize)
{
    for (int i = 0; i < source.Count(); i+=batchSize)
    {
        yield return source.Skip(i).Take(batchSize);
    }
}

通过这种方式,您可以按批处理大小拆分列表,如果不能按批处理大小划分项目计数,则最后一次迭代将产生其余的可枚举值.

that way you split the list by batchSize of items, and if the count of the items is not dividable by batch size, the last iteration will yield the rest of the enumerable.

这篇关于Linq以四元组的形式获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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