拆分一个IEnumerable&LT; T&GT;成固定大小的块(返回一个IEnumerable&所述; IEnumerable的&所述; T&GT;化合物其中的内序列的长度是固定的) [英] Split an IEnumerable<T> into fixed-sized chunks (return an IEnumerable<IEnumerable<T>> where the inner sequences are of fixed length)
问题描述
我要带一个的IEnumerable&LT; T&GT;
键,把它分解成固定大小的块
I want to take an IEnumerable<T>
and split it up into fixed-sized chunks.
我有这个,但由于所有的列表创建/复制似乎不雅:
I have this, but it seems inelegant due to all the list creation/copying:
private static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> items, int partitionSize)
{
List<T> partition = new List<T>(partitionSize);
foreach (T item in items)
{
partition.Add(item);
if (partition.Count == partitionSize)
{
yield return partition;
partition = new List<T>(partitionSize);
}
}
// Cope with items.Count % partitionSize != 0
if (partition.Count > 0) yield return partition;
}
是不是有什么更地道?
Is there something more idiomatic?
编辑:虽然这已被标记为重复<一个href=\"http://stackoverflow.com/questions/3210824/divide-array-into-an-array-of-subsequence-array\">Divide数组子阵列该数组是不是 - 有分裂的数组问题的交易,而这是关于的IEnumerable&LT; T&GT;
。除了这个问题要求的最后一个子被填充。这两个问题是密切相关的,但都是不一样的。
Although this has been marked as a duplicate of Divide array into an array of subsequence array it is not - that question deals with splitting an array, whereas this is about IEnumerable<T>
. In addition that question requires that the last subsequence is padded. The two questions are closely related but aren't the same.
推荐答案
您可以尝试落实自己的上述这样的间歇法:
You could try to implement Batch method mentioned above by your own like this:
static class MyLinqExtensions
{
public static IEnumerable<IEnumerable<T>> Batch<T>(
this IEnumerable<T> source, int batchSize)
{
using (var enumerator = source.GetEnumerator())
while (enumerator.MoveNext())
yield return YieldBatchElements(enumerator, batchSize - 1);
}
private static IEnumerable<T> YieldBatchElements<T>(
IEnumerator<T> source, int batchSize)
{
yield return source.Current;
for (int i = 0; i < batchSize && source.MoveNext(); i++)
yield return source.Current;
}
}
我抓住从这个code <一个href=\"http://blogs.msdn.com/b/pfxteam/archive/2012/11/16/plinq-and-int32-maxvalue.aspx\">http://blogs.msdn.com/b/pfxteam/archive/2012/11/16/plinq-and-int32-maxvalue.aspx.我觉得这个方法有多个集合枚举使用跳过/送方法,它是懒惰的性能更好。
I've grabbed this code from http://blogs.msdn.com/b/pfxteam/archive/2012/11/16/plinq-and-int32-maxvalue.aspx. I think this approach has better performance that multiple collection enumeration using Skip/Take methods and it's lazy.
这篇关于拆分一个IEnumerable&LT; T&GT;成固定大小的块(返回一个IEnumerable&所述; IEnumerable的&所述; T&GT;化合物其中的内序列的长度是固定的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!