2016-11-19 21 views
0

我試圖從這個方法被調用時從對象列表中隨機獲取一個字符串id,然後從列表中刪除該id,所以當我打電話時我不會得到該id的一個副本該方法再次。我知道如何使用字符串列表來完成它,但是當列表中有對象時,我不知道如何去做。c#在對象列表中沒有重複的隨機字符串

我嘗試做這樣的事情,但它不起作用。

public string RandomHotelID() 
    { 
     Random gen = new Random(); 
     string Id; 
     foreach(Hotels hotel in LHotels) 
     { 
      int findex = gen.Next(0, LHotels.Count); 
      Id = hotel.HotelId[findex]; 

     } 

     return Id; 
    } 

回答

0

你不需要foreach循環,和這裏的原因:

//Pseudocode of what you want 
i <- generate random number between 0 and the number of Hotels 
return the hotel id string of the hotel at i 

通知,沒有參與循環。那這是否

代碼(注意,我構建了隨機的私有實例變量,以避免隨意性的問題):

class RandomHotelId { 
    Random r = new Random(); 
    public string RandomHotelID() 
    { 
     return LHotels[r.next(0, LHotels.Count)].HotelId; 
    } 
} 
+0

將如何修改這個避免了重複的ID? –

+0

你可以跟蹤已經在某種集合中檢索到的id,並且'while(nextValue not in collection)nextValue < - 獲取不同的值' –

+0

Ah k,非常感謝提示 –