使用LINQ将集合拆分为‘N’部件?有什么好办法把一个集合分割成n和LINQ的零件?当然也不一定均衡。也就是说,我想将集合划分为子集合,每个子集合都包含元素的子集,其中最后一个集合可以是粗糙的。
3 回答
扬帆大鱼
TA贡献1799条经验 获得超9个赞
static class LinqExtensions{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
int i = 0;
var splits = from item in list
group item by i++ % parts into part select part.AsEnumerable();
return splits;
}}
胡子哥哥
TA贡献1825条经验 获得超6个赞
没有昂贵的乘法、除法或模运算符 所有操作均为O(1)(见下文注) 为IEnumerable<>源代码工作(不需要计数属性) 简约
public static IEnumerable<IEnumerable<T>>
Section<T>(this IEnumerable<T> source, int length){
if (length <= 0)
throw new ArgumentOutOfRangeException("length");
var section = new List<T>(length);
foreach (var item in source)
{
section.Add(item);
if (section.Count == length)
{
yield return section.AsReadOnly();
section = new List<T>(length);
}
}
if (section.Count > 0)
yield return section.AsReadOnly();}myEnum.Section(myEnum.Count() / number_of_sections + 1)
- 3 回答
- 0 关注
- 440 浏览
添加回答
举报
0/150
提交
取消
