EN
C# / .NET - pick random string from array of strings
2 points
In C# / .NET it is possible to get element with [ ]
operator or IEnumerable<TSource>.ElementAt
method. To get random element, random index from Random
class is necessary.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
4
class Program
5
{
6
public static void Main(string[] args)
7
{
8
Random random = new Random();
9
10
string[] array = new string[]
11
{
12
"A", "B", "C", "D", "E", "F"
13
};
14
15
for (int i = 0; i < 10; ++i)
16
{
17
int index = random.Next(array.Length);
18
string entry = array[index]; // array.ElementAt(index);
19
20
Console.WriteLine(entry);
21
}
22
}
23
}
Output:
xxxxxxxxxx
1
B
2
B
3
E
4
A
5
E
6
B
7
B
8
D
9
D
10
C