AJ Sloan AJ Sloan - 21 days ago 5
C# Question

c# Random string without duplicate in list of object

I am trying to grab a random string id from a list of objects when this method is called then remove that id from the list so i wont get a duplicate of that id when i call the method again. I know how to do it with a list of strings, but i dont know how you do it when you have objects in a list.

I try doing something like this, but it does not work.

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

Answer

You don't need the foreach loop, and here's why:

//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

Notice, no looping involved.

Code that does that (note, I construct the Random as a private instance variable to avoid randomness problems):

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