I really like the algorithm shown below for splitting a list into sublists of a fixed size. It might not be the most an efficient algorithm (edit: at all).
I'd like something that has a good balance of readability, elegance, and performance. The problem is, most algorithms I find in C# require the yield
keyword, which is not available if you're using .NET 3.5 in Visual Studio 2010 ;)
public IEnumerable<IEnumerable<T>> Partition<T>(IEnumerable<T> source, int size)
{
if (source == null)
throw new ArgumentNullException("list");
if (size < 1)
throw new ArgumentOutOfRangeException("size");
int index = 1;
IEnumerable<T> partition = source.Take(size).AsEnumerable();
while (partition.Any())
{
yield return partition;
partition = source.Skip(index++ * size).Take(size).AsEnumerable();
}
}
I tried rewriting this in VB, but had to use a second list to collect results into, which ended up taking significantly more time than the implementation above.
I'm looking for another algorithm I could use in VB.NET, but most of the results run into the issue of having to basically load everything into the memory instead of the ability to dynamically produce the results a la generators in python. Not an huge issue, but not as ideal as it would be with yield return
.
Is there a good, recommended algorithm for doing this in VB.NET? Would I have to create something implementing IEnumerator
to generate the results on demand?