本文介绍了把一个大的IEnumerable到项目的固定量较小的IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了支持只接受项目(5项),我想变换LINQ导致成总是包含项目的那套量项目的小团体的特定量的API。

In order to support an API that only accepts a specific amount of items (5 items), I want to transform a LINQ result into smaller groups of items that always contain that set amount of items.

假定列表 {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 17,18}​​

我希望得到一个最大的5个项目每个

I want to get three smaller lists of a maximum of 5 items each

{1,2,3,4,5}

{6,7,8,9,10}

{11,12,13,14,15}

{16,17,18}​​

我怎样才能做到这一点与LINQ?我假设它要么涉及盘算如何编写总结,但我有麻烦了。

How can I do that with LINQ? I'm assuming that it either involves Group or Aggregate, but I'm having trouble figuring how to write that.

推荐答案

尝试是这样的:

var result = items.Select((value, index) => new { Index = index, Value = value})
                  .GroupBy(x => x.Index / 5)
                  .Select(g => g.Select(x => x.Value).ToList())
                  .ToList();



它的工作原理是根据其原始列表索引分区中的项目成组。

It works by partitioning the items into groups based on their index in the original list.

这篇关于把一个大的IEnumerable到项目的固定量较小的IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 15:36