ajb*_*run 6 c# linq grouping partitioning group-by
我知道制作一种方法将项目列表分组(例如)不超过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;
});
return groups;
}
Run Code Online (Sandbox Code Playgroud)Ant*_*Chu 10
这是使用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();
}
Run Code Online (Sandbox Code Playgroud)
我想你正在寻找这样的东西:
return source.Select((x, idx) => new { x, idx })
.GroupBy(x => x.idx / itemsPerGroup)
.Select(g => g.Select(a => a.x));
Run Code Online (Sandbox Code Playgroud)
您需要将返回类型更改为 IEnumerable<IEnumerable<TSource>>
| 归档时间: |
|
| 查看次数: |
4768 次 |
| 最近记录: |