使用数组中的随机项填充列表框

时间:2012-10-14 13:16:31

标签: c# arrays random listbox

我有两个阵列;富贵车&汽车。我想用随机物品填充lstBoxGarage(4辆来自汽车,1辆来自richcars) 现在我不知道该怎么做,我希望你们能帮助我。 目前我有这个,但这显然填满了所有项目的列表框..

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

2 个答案:

答案 0 :(得分: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--;
 }

答案 1 :(得分: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);
        }
    }

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

相关问题