generic-list

Randomize a List<T>

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-25 21:35:13
问题 What is the best way to randomize the order of a generic list in C#? I\'ve got a finite set of 75 numbers in a list I would like to assign a random order to, in order to draw them for a lottery type application. 回答1: Shuffle any (I)List with an extension method based on the Fisher-Yates shuffle: private static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n];