Search code examples
c#randomhashset

Get random element from HashSet<T>?


I'm using the following piece of code to load my text file into a HashSet<string>.

HashSet<string> hashs = new HashSet<string>(File.ReadLines("textFile.txt"));

Am wondering if there is any easy way to get a random line from it?

Lets assume the textFile.txt contains 10 lines, I would like to randomize and grab one of those existing lines.


Solution

  • Random randomizer = new Random();
    string[] asArray = hashs.ToArray()
    string randomLine = asArray[randomizer.Next(asArray.length)];