I have this pattern where I need to select any random element from a list, other than the current one (passed as argument). I came up with this method:
public Element GetAnyoneElseFromTheList(Element el)
{
Element returnElement = el;
Random rndElement = new Random();
if (this.ElementList.Count>2)
{
while (returnElement == el)
{
returnElement = this.ElementList[rndElement.Next(0,this.ElementList.Count)];
}
return returnElement;
}
else return null;
}
But that while loop has been bothering me for days and nights and I need to get some sleep. Any other good approaches to this? ie. something that returns in a fixed-number-of-steps ?
Edit : In my case, the list is guaranteed to contain the “el” Element to avoid, and the list contains no duplicates, but it would be interesting to see some more general cases aswell.
1 Answer