Click here to Skip to main content
15,905,874 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Like the question says, is it possible to not display the previous random item from a list? basically I have a List:

C#
List<Animal> animals = new List();


That have the following properties

C#
public string Name
{
    get { return _name; }
    set { _name = value; }
}

public string Specie
{
    get { return _specie; }
    set { _specie = value; }
}


What I have tried:

This object name or specie is then being randomly generated to text boxes:

C#
private string RandomAnimal(Random r)
{
    if (random.Next(2) == 0)
    {
        txtSpecie.Text = randomAnimal.Specie;
        return randomAnimal.Specie;
    }
    else
    {
        txtName.Text = randomAnimal.Name;
        return randomAnimal.Name;
    }
}


Lets say that random animal Name has been shown on the textbox. Is it possible to write a method perhaps that will insure that the same name that was previously displayed in textbox will not be displayed anymore?

Thanks in advance
Posted
Updated 1-Nov-17 10:47am

If I got you, then you need to avoid replicates in random selections. Have a look at my Random extraction of 5 cards from a deck[^]. It is C++ code, but I guess you could easily get the idea.
 
Share this answer
 
Simple solution?
Copy the List:
C#
List<Animal> takeFromHere = new List<Animal>(animals)

and use that for your random selection. When you select an item, remove it from the collection. If the collection is now empty, re-fill it.
 
Share this answer
 
Comments
fellanmorgh 3-Nov-17 16:50pm    
Hi, thanks for reply. Didn't have a chance to take a look up until now. I forgot to mention that the List<animal> animals is being passed through parameters as it is being filled in different user control and the filled list is being passed to the current user control that the random method is in. So does that solution would still work? and if yes could you please show me some kind of example? thanks :)
OriginalGriff 4-Nov-17 4:37am    
Yes. See code above.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900