I can’t get my head around how to do this.
I have a collection of objects
{ object1, object2, object3, object4 }
I want to break up this collection into a collection of collections, so that I end up with something that looks like
{ { object1, object2}, {object2, object3}, {object3, object4} }
I’ve found how to chunk the collection into smaller ones, but it is the repeating of the previous item in each collection that is doing my head in.
Any help greatly appreciated!
My current chunk method (taken from another question on here) is
public static IEnumerable<IEnumerable<T>> Chunk<T>(this IEnumerable<T> source, int size)
{
return source.Select((x, i) => new { Index = i, Value = x })
.GroupBy(x => x.Index / size)
.Select(x => x.Select(v => v.Value));
}
EDIT
This works, but is there a better way?
public static ICollection<ICollection<T>> BreakUp<T>(this IEnumerable<T> polylines, int size)
{
var results = new Collection<ICollection<T>>();
results.Add(new Collection<T>());
var x = 0;
for (var i = 0; i < polylines.Count(); i++)
{
results[x].Add(polylines.ElementAt(i));
if (results[x].Count() % size == 0 && i != polylines.Count() - 1)
{
x++;
results.Add(new Collection<T>());
results[x].Add(polylines.ElementAt(i));
}
}
return results;
}
You can simplify your code like this:
Test:
Here’s a solution that iterates
sourceonly once:Results: