Mister Epic
Mister Epic

Reputation: 16733

Group objects into fixed-sized collections

I am attempting to take a collection of entries in a zip file and group related ones together. I know there should be 4 entries to a group. I tried the following:

var entryGroups = zipArchive.Entries
            .OrderBy(entry => entry.FullName)
            .Select((entry, index) => new {index, entry})
            .GroupBy(entry => entry.index % groupSize)
            .Select(group => group.Select(grouping => grouping.entry));

Unfortunately, that gives me 4 large groups, whereas I am looking for many groups which have 4 entries each.

Upvotes: 1

Views: 193

Answers (2)

ryanyuyu
ryanyuyu

Reputation: 6486

Replace the remainder operator % with integer division /

Use the reminder operator with create only n groups, Not groups of size n. Use integer division (/) for dividing into n groups. Note that the final group might be a few elements short (it will be the remainder).

Upvotes: 1

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

Might be worth trying with / rather than %

var entryGroups = zipArchive.Entries
        .OrderBy(entry => entry.FullName)
        .Select((entry, index) => new {index, entry})
        .GroupBy(entry => entry.index / groupSize)
        .Select(group => group.Select(grouping => grouping.entry));

Upvotes: 2

Related Questions