I am creating a HashSet in C# of type int. The HashSet is filled with randomly generated numbers. I'd like to select one of these numbers from the it at random and return it to the user. The problem is, I only see solutions that return the index of the item in the HashSet not the actual value. I'd like to know how I can access the value of my HashSet items.
Here's what I have at the moment, first I create a list from 10 to 20 which forms part of my list control, the reason for this is to set a limit on how many items a list can hold.
List<int> list_length = Enumerable.Range(10, 20).ToList();
I then iterate over list_length and add a random number to my primary list which is called hash_values
private readonly HashSet<int> hash_values = new HashSet<int>();
foreach (var i in list_length)
{
hash_values.Add(rnd.Next(10, 20));
}
I then access the hash_values list and return a random value from it.
int get_random_number = rnd.Next(hash_values.Count());
return Json(get_random_pin);
You'll notice that the random return is actually selecting a value from the lists total count. This is no use. What I'd like to do is pick an item at random and turn it's value not the index.
Let's say I have a list with 5 values, the hash_values table will store it like this:
[0] 100
[1] 200
[2] 300
[3] 400
[4] 500
Returning something like a random number from the lists total count will only select the index, so I would receive [1] instead of 100. So, how do I return the value instead of the index?