2012-10-14 42 views
1

我有兩個數組;富豪車&汽車。我想用隨機物品填滿lstBoxGarage(4輛汽車和1輛富豪車) 現在我不知道該怎麼做,我希望你們能幫我一把。 目前,我有這個,但是這填滿了明顯的所有項目的列表框..使用數組中的隨機項填充列表框

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

正如其他人指出的[你的其他問題]的答案(http://stackoverflow.com/questions/12880707/putting-two-dimensional-array-in-listbox),它會更好*不*使用二維數組,而是定義您自己的「Car」類。 – Adam

+0

隨機嘗試從0到每個數組長度-1的範圍內的數字並添加到列表中。隨機可以使用:'new Random()。next(0,richcars.GetLength(0)-1))'。對於汽車的4輛車,檢查它是否已經包含了'lstBoxGarage.Contains(汽車對象)的車;' –

+0

但*不*每次都創建一個新的'隨機',這根本不會是隨機的;重複使用相同的靜態「Random」,以便每次調用「Next」。 – Adam

回答

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

這可能會多次添加同一輛車;可能不是OP想要的。 – Adam

+0

我添加了一個條件來防止重複。 – Adil

+0

嗯,這有點作品,但它增加了一個車10次,然後另一輛車:/ – vlovystack

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

但是請注意,這只是存儲車名稱,以存儲價格,您應該創建一個名稱和價格屬性的汽車類