ninia sabadze
ninia sabadze

Reputation: 1

How to merge unknown amount of arrays?

I'm building a driving license exam practice test. Users can choose multiple categories to get questions from. I want to take tickets from this arrays and put them all in one array. This is my code:

public Ticket[] GetTickets(int numOfCat)
    {
        bool getTicks = true;
        if (getTicks)
        {
            System.Console.WriteLine(DrivingLicenceStorage.Categories.Length);
            for (int i = 0; i < numOfCat; i++)
            {
                System.Console.Write($"Enter category N{i + 1}: ");
                var Ids = Convert.ToInt32(Console.ReadLine());
                if (Ids > DrivingLicenceStorage.Categories.Length)
                {
                    System.Console.WriteLine("Invalid Input");
                    System.Console.WriteLine("Try Again");
                    i--;
                }
                else
                {
                    Tickets = DrivingLicenceStorage.Categories.ElementAt(Ids).Tickets;
                    getTicks = false;
                }
            }

        }
        

        return Tickets;
    }

The problem is that Tickets gets the tickets from the last category user enters. How do I merge all the chosen categories' tickets?

Upvotes: 0

Views: 76

Answers (1)

Heinzi
Heinzi

Reputation: 172200

Arrays are not the right data type for lists with a dynamic number of elements. You can use a List<Ticket> instead.

Example code:

var ticketList = new List<Ticket>();
...
// repeat as often as required 
​ticketList.AddRange(DrivingLicenceStorage.Categories.ElementAt(Ids).Tickets); ​   
...
return ticketList.ToArray();

Upvotes: 3

Related Questions