Languages
[Edit]
EN

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

2 points
Created by:
Root-ssh
174740

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

Alternative titles

  1. C# / .NET - pick random text from array of texts
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# / .NET - random

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join