Get random item from hashset?

Im using the following code snippet to load my text file into hashset .

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

I wonder if there is any easy way to get a random string from it?

Assuming textFile.txt contains 10 lines, I would like to randomize and capture one of these existing lines.

+8
c # hashset
source share
4 answers
 Random randomizer = new Random(); string[] asArray = hashs.ToArray() string randomLine = asArray[randomizer.Next(asArray.length)]; 
+10
source share

A simple answer, such as accepted, is possible without listing the entire array each time:

 private static readonly Random random = new Random(); private static readonly HashSet<T> hashset = new HashSet<T>(); ... T element = hashset.ElementAt(random.Next(hashset.Count)); 
+24
source share

You can generate a random number between 0 and the size of the set, and then iterate through the setup until you reach an element whose index matches the number of the generated number. Then select this item as a random item.

+2
source share

Or maybe a more general solution for any enumerated

 public static class RandomExtensions { private static readonly Random rnd = new Random(); private static readonly object sync = new object(); public static T RandomElement<T>(this IEnumerable<T> enumerable) { if (enumerable == null) throw new ArgumentNullException("enumerable"); var count = enumerable.Count(); var ndx = 0; lock (sync) ndx = rnd.Next(count); // returns non-negative number less than max return enumerable.ElementAt(ndx); } } 
+1
source share

All Articles