select random item from list c# code example
Example 1: random from list c#
list[Random.Range(0, list.Count)];
Example 2: c# pick a random item from array
string[] names = new string[] { "name1", "name2", "name3" };
Random rnd = new Random();
int index = rnd.Next(names.Length);
Console.WriteLine($"Name: {names[index]}");
Example 3: c# random choice
using System;
using System.Collections.Generic;
namespace Demo {
class Program {
static void Main(string[] args) {
var random = new Random();
var list = new List<string>{ "one","two","three","four"};
int index = random.Next(list.Count);
Console.WriteLine(list[index]);
}
}
}
Example 4: get random value from list c#
public List<T> GetRandomFromList<T>(List<T> passedList, int numberToChoose)
{
System.Random rnd = new System.Random();
List<T> chosenItems = new List<T>();
for (int i = 1; i <= numberToChoose; i++)
{
int index = rnd.Next(passedList.Count);
chosenItems.Add(passedList[index]);
}
return chosenItems;
}