Im using the following piece of code to load my text file into a hashset.
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 asume the textFile.txt contains 10 lines, i would like to randomize and grab one of those existing lines.
If you are planning on drawing multiple random values, the efficient way would be to use a Dictionary with integer keys to store the information.
HashSet<string> hashs = new HashSet<string>();
Dictionary<int, string> lookup = new Dictionary<int, string>();
foreach (string line in File.ReadLines("textFile.txt")) {
if (hashs.Add(line)) {
lookup.Add(lookup.Count, line);
}
}
int randomInt = new Random().Next(lookup.Count);
string randomLine = lookup[randomInt];
(In this example, you could use a List instead, but with a dictionary you can also remove individual elements without affecting the order).
Random randomizer = new Random();
string[] asArray = hashs.ToArray()
string randomLine = asArray[randomizer.Next(asArray.length)];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With