Share via

List sorting problem

Stephan Gross 1 Reputation point
2022-02-23T10:34:46.36+00:00

Hi there

I am wondering how to best solve a list sorting problem.

Mentioned list initially consists of recipients ordered by First + Last Name. A given number of recipients fit on a report sheet to be printed.
Now, the report sheets are stacked upon each other and then cut vertically. The entire list of recipients must be rearranged in a sort of way that each resulting pile of cuttings is contiguously ordered by First + Last Name..

This is a working solution I came up with – but it isn’t very efficient.
I clone the list and iterate the clone multiple times to bypass recipients of previous pages and to collect every n-th recipient for the current page:

public void RearrangeRecipients(byte recipientsPerSheet)
        {
            // Clone and clear all food card recipients
            var clonedRecipients = new List<IFoodCardRecipient>(recipientsList);
            recipientsList.Clear();

            // Determine sheet count
            var sheetCount = Math.Ceiling((double)clonedRecipients.Count / recipientsPerSheet);
            for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++)
            {
                // Bypass recipients of previous pages, then take every n-th recipient for the current page
                var recipientsCurrentSheet = clonedRecipients.Skip(sheetIndex).Where((recipient, index) => index % sheetCount == 0);
                recipientsList.AddRange(recipientsCurrentSheet);
            }
        }

Thanks for any tipps :)

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Stephan Gross 1 Reputation point
    2022-02-23T12:19:00.12+00:00

    Turns out that creating a second for - loop starting at sheet index (skip) and then incrementing by sheet count rather than iterating each element is significantly faster on larger collections :)
    Thanks for the help anyway ;)

    177186-rearrage-recipient.png

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.