1

我有两个数组;富豪汽车和汽车。我想用随机物品(4 个来自汽车和 1 个来自 Richcars)填充 lstBoxGarage 现在我不知道该怎么做,我希望你们能帮助我。目前我有这个,但这显然会用所有项目填充列表框..

  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]);
  }

任何人都可以帮我解决这个随机的事情吗?

这是我的两个数组

          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" }
};
4

2 回答 2

1

您可以使用 Random 类生成随机数

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--;
 }
于 2012-10-14T13:19:44.630 回答
0

试试这个 :

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);
        }
    }

但请注意,这仅存储汽车名称,要存储价格,您应该创建一个具有名称和价格属性的 Car 类

于 2012-10-14T13:43:12.993 回答