2015-11-13 25 views
1

我是新的C#和具有下面的一段代碼列表隨機整數:C#獲取在每個循環

int[] ids = { 190483, 184943, 192366, 202556, 169051, 177388, 170890, 146562, 189509 }; 

for (var i=0; i<50; i++) 
{ 
    int randomID = *randomNumberFromIDList*; 
    Console.WriteLine("Random ID:" + randomID); 
} 

正如你所看到的,我希望做的是每次循環分配並顯示一個隨機ID,其中randomID被設置爲一個int。

有沒有一種簡單的方法來做到這一點?

+0

你需要一個Random類的實例,比如它叫'random'。然後,只需調用'random.Next(ids.Count)'並將其用作索引。 –

回答

3

創建Random實例,並調用Next(int, int)功能inclusive lowest numberexclusive highest number之間獲得數:

int[] ids = { 190483, 184943, 192366, 202556, 169051, 177388, 170890, 146562, 189509 }; 

var random = new Random(); 
for (var i=0; i<50; i++) 
{ 
    int randomID = ids[random.Next(0, ids.Length)]; 
    Console.WriteLine("Random ID:" + randomID); 
} 
+1

@GiorgiNakeuri如上所述,第二個參數是_exclusive_上限。因此'Next(0,1)'將始終生成'0'。請參見[msdn](https://msdn.microsoft.com/en-us/library/2dx6wyd4%28v=vs.110%29.aspx) –

1

可以使用Random類,這和生成0和數組的長度之間的隨機數:

var r = new Random(); 
for (var i=0; i<50; i++) 
    Console.WriteLine("Random ID:" + ids[r.Next(0, ids.Length)]); 
0

您可以使用隨機生成一個從0開始到數組大小的索引,並使用此索引獲取數組的位置並獲得一個隨機ID。

int[] ids = { 190483, 184943, 192366, 202556, 169051, 177388, 170890, 146562, 189509 }; 

var random = new Random(); 

for (var i = 0; i < 50; i++) 
{ 
    int arrayPos = random.Next(0, ids.Count() - 1); 
    int randomID = ids[arrayPos]; 
    Console.WriteLine("Random ID:" + randomID); 
}