1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
using System;
using System.Collections.Generic;
namespace PickRandom
{
class Program
{
static void Main()
{
Console.WriteLine("Hello World!");
List<string> lst = new List<string>() { "Item A", "Item B", "Item C", "Item D" };
string s = string.Empty;
while (s != null)
{
s = lst.PickRandom();
Console.WriteLine(s);
}
}
}
static class MyExtensions
{
public static T PickRandom<T>(this List<T> list)
{
if (list.Count > 0)
{
int idx = (new Random()).Next(list.Count);
T res = list[idx];
list.RemoveAt(idx);
return res;
}
else
{
return default;
}
}
}
} |
Partager