2016-11-19 49 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,非常感谢提示 –