vlovystack
vlovystack

Reputation: 703

Filling a listbox with random items from array

I've got two arrays; richcars & cars. I want to fill up lstBoxGarage with random items (4 from cars and 1 from richcars) Now I have no idea how to do this, and I was hoping you guys could help me out. At the moment I have this, but this fills the listbox with all the items obviously..

  for (int i = 0; i < richcars.GetLength(0); i++)
  {
    lstBoxGarage.Items.Add(richcars[i, 0]);
  }

  for (int i = 0; i < cars.GetLength(0); i++)
  {
    lstBoxGarage.Items.Add(cars[i, 0]);
  }

Could anyone help me with this random thing?

Here are my two arrays

          string[,] richcars = new string[10, 2] {
    { "Porsche Cayenne Turbo", "108000" },
    { "Porsche Panamera GTS", "111000"},
    { "Porsche 911 Carrera 4S", "105000"},
    { "Porsche Cayman S", "65000"},
    { "Porsche 911 Turbo", "140000"},
    { "Ferrari California", "190000"},
    { "BMW M3", "60000"},
    { "BMW M6", "105000"},
    { "Maserati GranTurismo S", "125000"},
    { "Audi R8 V10", "150000" }
};

      string[,] cars = new string[6, 2] {
    { "VW Golf GTI", "25000" },
    { "Mini Cooper S", "25000" },
    { "Jeep Wrangler", "25000" },
    { "Audi A4", "35000" },
    { "Nissan 370Z ", "35000" },
    { "Ford Focus ST", "25000" }
};

Upvotes: 1

Views: 1611

Answers (2)

Adil
Adil

Reputation: 148120

You can use Random class to generate random numbers

int limit = richcars.GetLength(0)
 for (int i = 0; i < limit ; i++)
 {
    Random random = new Random();

    int randomNumber = random.Next(0, limit);
    if (lstBoxGarage.FindStringExact(richcars[randomNumber, 0]) == -1)
       lstBoxGarage.Items.Add(richcars[randomNumber , 0]);
    else
        i--;
 }

Upvotes: 1

Ta Duy Anh
Ta Duy Anh

Reputation: 1488

Try this :

Random random = new Random();
lstBoxGarage.Add(richcars[random.Next(0,richcars.GetLength(0)),0]);
for (int i = 0; i < 4; i++)
    {
        var car = cars[random.Next(0,cars.GetLength(0)),0];
        if (lstBoxGarage.Contains(car))
        {
            i--;
        }
        else
        {
            lstBoxGarage.Add(car);
        }
    }

But notice that this only store the car name, to store with the price, you should create a Car class with name and price properties

Upvotes: 0

Related Questions