Languages
[Edit]
EN

C# / .NET - pick random string from array of strings

2 points
Created by:
Root-ssh
68500

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.

1. Random index example

using System;
using System.Linq;

class Program
{
	public static void Main(string[] args)
	{
		Random random = new Random();

		string[] array = new string[]
		{
			"A", "B", "C", "D", "E", "F"
		};

		for (int i = 0; i < 10; ++i)
		{
			int index = random.Next(array.Length);
			string entry = array[index]; // array.ElementAt(index);

			Console.WriteLine(entry);
		}
	}
}

Output:

B
B
E
A
E
B
B
D
D
C

References

  1. Random.Next Method - Microsoft Docs
  2. Enumerable.ElementAt Method - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join