如何用linq构建批处理/桶 [英] How to build batches/buckets with linq
本文介绍了如何用linq构建批处理/桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 内存友好:即使在每个批次中,项目也必须延迟加载(
IEnumerable< IEnumerable< T>>
,不包括解决方案构建数组)(
- 与
Skip()
和Take()
) - 如果不是必需的,则遍历整个输入(排除带有
GroupBy
的解决方案)
这个问题与以下相似但限制较多:
解决方案
最初由在linq创建批次中的@Nick_Whaley发布,但不是最好的反应,因为问题的表述是不同的:
试试这个:
公共静态IEnumerable< IEnumerable< T>> Bucketize< T>(这个IEnumerable< T> items,int bucketSize)
{
var enumerator = items.GetEnumerator();
while(enumerator.MoveNext())
yield return GetNextBucket(enumerator,bucketSize);
}
私有静态IEnumerable< T> GetNextBucket< T>(IEnumerator< T>枚举器,int maxItems)
{
int count = 0;
do
{
yield return enumerator.Current;
count ++;
if(count == maxItems)
yield break;
} while(enumerator.MoveNext());
}
诀窍是在内部枚举和外部枚举之间传递旧式枚举,以在两批之间启用延续。
I need to create batches from a lazy enumerable with following requirements:
- Memory friendly: items must be lazy loaded even within each batch (
IEnumerable<IEnumerable<T>>
, excludes solution building arrays) - the solution must not enumerate twice the input (excludes solutions with
Skip()
andTake()
) - the solution must not iterate through the entire input if not required (exclude solutions with
GroupBy
)
The question is similar but more restrictive to followings:
解决方案
Originally posted by @Nick_Whaley in Create batches in linq, but not the best response as the question was formulated differently:
Try this:
public static IEnumerable<IEnumerable<T>> Bucketize<T>(this IEnumerable<T> items, int bucketSize)
{
var enumerator = items.GetEnumerator();
while (enumerator.MoveNext())
yield return GetNextBucket(enumerator, bucketSize);
}
private static IEnumerable<T> GetNextBucket<T>(IEnumerator<T> enumerator, int maxItems)
{
int count = 0;
do
{
yield return enumerator.Current;
count++;
if (count == maxItems)
yield break;
} while (enumerator.MoveNext());
}
The trick is to pass the old-fashion enumerator between inner and outer enumeration, to enable continuation between two batches.
这篇关于如何用linq构建批处理/桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文