Search code examples
c#algorithmrazorengine

List of alphabet sort to display vertically


I have a list, containing the alphabet.

When outputting with foreach, i will currently receive this result:

  • A B C
  • D E F
  • G H I

What i would like to achieve is this

  • A D G
  • B E H
  • C F I

Ive tried the following, but really, i doesent find it a good or stable solution - and the letters/indexes are presented twice.

        @{
            var ie = 0;
            int sortI = 0;

}
            int columns = 3;
            int dictLength = ToShow.Count();
            int rows = dictLength/columns;

            int sortS = 1;
            List<int> hasKey = new List<int>();

            var newDict = new Dictionary<string, List<LoopItem> >();


            if( sort.Equals("alphabetically") )
            {

                while( sortI <= rows )
                {

                        <text>Column @( ToShow.Keys.ElementAt(sortI) ) - </text>

                        while( sortS <= ( columns ) )
                        {           
                                int index = (( sortS *  columns ) + sortI); //(( sortS *  columns ) + ( 1 + sortI ));

                                if( hasKey.Contains(index) ) { continue; } else
                                {

                                    <text>Column @( ToShow.Keys.ElementAt(index) ) - </text>
                                    sortS++;
                                    hasKey.Add(index);
                                }
                        }
                            <text><br /></text>
                        sortS = 1;
                        sortI++;
                }

                sortS = 1;
                sortI = 1;
                <text><hr /></text>
                foreach( var item in ToShow )
                {
                        <text><br/>::Række 1::<br /></text>
                    while( columns >= sortS )
                    {
                            <text>Indsæt @(sortI+sortS)<br /></text>
                            sortS++;
                    }

                    sortI++;
                    sortS = 1;
                }

            }

        }

Are there any algorithm for this kind of stuff? Or a simple function?

Thanks in advance


Solution

  • If you know how many letters you want to present on each row you could do something like this:

    var alphabet = new []{'A', 'B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    var rows = 3;
    var alphabetIndex = 0;
    
    for(var row = 0; row < rows; row++) {
        for(var letter = alphabetIndex; letter < 26; letter += rows) {
            Console.Out.Write(alphabet[letter] + " ");
            if(letter + rows >= 26)
                alphabetIndex = (letter + rows) - 26;
        }
        Console.Out.WriteLine();
    }
    

    Rows will set how many rows you want, other than that it should work out for you.