我有一个问题,不知道如何最好地编写一种方法,以便将一系列项目分组为(例如)不超过3个项目的组。我创建了下面的方法,但在返回之前没有对组执行
第一次枚举时是正确的,但任何其他枚举都会出错,因为两个变量(i和groupKey)似乎在迭代之间被记住。
所以问题是:
ToList
,如果多次枚举列表,则会出现问题。第一次枚举时是正确的,但任何其他枚举都会出错,因为两个变量(i和groupKey)似乎在迭代之间被记住。
所以问题是:
- Is there a better way to do what I'm trying to achieve?
Is simply ToListing the resulting group before it leaves this method really such a bad idea?
public static IEnumerable<IGrouping<int, TSource>> GroupBy<TSource> (this IEnumerable<TSource> source, int itemsPerGroup) { const int initial = 1; int i = initial; int groupKey = 0; var groups = source.GroupBy(x => { if (i == initial) { groupKey = 0; } if (i > initial) { //Increase the group key if we've counted past the items per group if (itemsPerGroup == initial || i % itemsPerGroup == 1) { groupKey++; } } i++; return groupKey; }); return groups; }
Batch
方法。 - Sergey Berezovskiy