EN
C#/.NET - get random element from set
13 points
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
5
namespace Test
6
{
7
class Program
8
{
9
public static void Main(string[] args)
10
{
11
Random random = new Random();
12
13
HashSet<string> set = new HashSet<string>()
14
{
15
"A", "B", "C", "D", "E", "F"
16
};
17
18
for (int i = 0; i < 10; ++i)
19
{
20
int index = random.Next(set.Count);
21
string entry = set.ElementAt(index);
22
23
Console.WriteLine(entry);
24
}
25
}
26
}
27
}
Output:
xxxxxxxxxx
1
A
2
F
3
C
4
B
5
A
6
E
7
C
8
D
9
A
10
F
Note: in above example Enuberable.ElementAt
Linq method has been used to get element.