Reputation: 1015
I got following error at returns lines:
"Cannot implicity convert type using System.Collections.Generic.List<T> to T"
I do not understand why this error is thrown, my return type is IEnumerable, can you see error here?
public static IEnumerable<T> Batch<T>(this IEnumerable<T> collection, int batchSize)
{
List<T> nextbatch = new List<T>(batchSize);
foreach (T item in collection)
{
nextbatch.Add(item);
if (nextbatch.Count == batchSize)
{
yield return nextbatch;
nextbatch = new List<T>(batchSize);
}
}
if (nextbatch.Count > 0)
yield return nextbatch;
}
Upvotes: 0
Views: 3110
Reputation: 341
Method return type is IEnumerable<T>
with yield should return T not List<T>
for more information on how to use yield yield
Upvotes: 0
Reputation: 391336
You're not saying "this method will return many collections of T", you're saying "this method will return many T's".
In other words, this is how you need to declare your method:
public static IEnumerable<IEnumerable<T>> Batch<T>(...)
^---notice 2 layers---^
However, assuming this method will always return lists that you don't want to retain ownership to, you should make it easier for the consumers by just stating the best type to begin with:
public static IEnumerable<List<T>> Batch<T>(...)
Upvotes: 2