我使用以下代码将我的文本文件加载到哈希集。
HashSet<string> hashs = new HashSet<string>(File.ReadLines("textFile.txt"));
想知道是否有任何简单的方法可以从中获取随机行?
假设 textFile.txt 包含 10 行,我想随机化并获取其中一行。
最佳答案
无需每次都枚举整个数组,就可以像公认的那样得到一个简单的答案:
private static readonly Random random = new Random();
private static readonly HashSet<T> hashset = new HashSet<T>();
...
T element = hashset.ElementAt(random.Next(hashset.Count));
关于c# - 从哈希集中获取随机元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10654292/