0

I'm struggling with something I'm sure I should be able to do quite quick with Linq-to-Obj

Have 27 flowers, need a collection of Flower[] containing 5 items split over, roughly 6 records;

List<Flowers[]> should contain 6 Flowers[] entities, and each Flowers[] array item should contain 5 flower objects.

I currently have something like:

List<Flowers[]> flowers;
int counter = 0;
List<Flowers>.ForEach(delegate (Flower item) {
    if (counter <= 5){
        // add flowers to array, add array to list
    }
});

I'm trying to optimise this as it's bulky.

[Update]

I can probably to an array push on objects, removing the items I'v already run through, but is there not an easier way?

2
  • So you are effectively looking to do the reverse of SelectMany() and break out a single collection of 27 objects into 6 groups of 5. Do you care which 5 are grouped together? Do they have to be in sequential groupings, or grouped by other criteria? Or can it be random? Commented Sep 18, 2012 at 9:43
  • I'm not too worried about the grouping, and random is totally acceptable. Commented Sep 19, 2012 at 6:52

1 Answer 1

1
var ITEMS_IN_GROUP = 5;
var result = list.Select((Item, Index) => new { Item, Index })
                 .GroupBy(x => x.Index / ITEMS_IN_GROUP)
                 .Select(g => g.Select(x=>x.Item).ToArray())
                 .ToList();

You may also want to try morelinq's Batch

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.