将列表分组为每组 X 项的组 [英] Grouping lists into groups of X items per group
问题描述
我在了解将项目列表分组为(例如)不超过 3 个项目的组的最佳方法时遇到了问题.我已经创建了下面的方法,但是在返回之前没有在组上执行 ToList
,如果列表被多次枚举,我会遇到问题.
I'm having a problem knowing the best way to make a method to group a list of items into groups of (for example) no more than 3 items. I've created the method below, but without doing a ToList
on the group before I return it, I have a problem with it if the list is enumerated multiple times.
第一次枚举是正确的,但任何额外的枚举都会被抛弃,因为两个变量(i 和 groupKey)似乎在迭代之间被记住了.
The first time it's enumerated is correct, but any additional enumeration is thrown off because the two variables (i and groupKey) appear to be remembered between the iterations.
所以问题是:
- 有没有更好的方法来完成我正在努力实现的目标?
就是在结果组离开这个方法之前简单地列出结果组真的是个坏主意吗?
- 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;
}
推荐答案
这是使用 LINQ 执行此操作的一种方法...
Here's one way to do this using LINQ...
public static IEnumerable<IGrouping<int, TSource>> GroupBy<TSource>
(this IEnumerable<TSource> source, int itemsPerGroup)
{
return source.Zip(Enumerable.Range(0, source.Count()),
(s, r) => new { Group = r / itemsPerGroup, Item = s })
.GroupBy(i => i.Group, g => g.Item)
.ToList();
}
这篇关于将列表分组为每组 X 项的组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!