我知道制作一种方法将项目列表分组(例如)不超过3项的最佳方法时遇到问题.我已经创建了下面的方法,但是ToList在我返回之前没有对组进行操作,如果列表被多次枚举,我就会遇到问题.
第一次枚举是正确的,但是任何额外的枚举都会被抛弃,因为两个变量(i和groupKey)似乎在迭代之间被记住了.
所以问题是:
在它离开这个方法之前简单地将结果组ToListing真是个坏主意吗?
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; …Run Code Online (Sandbox Code Playgroud)