In various programming scenarios, the order of elements in randomly generic lists is a common operation. This article will introduce the best way to achieve this goal in C#.
The most recommended method is to use the Fisher-Yates shuffle algorithm, which is a well-known list randomization algorithm. To use this method, please define an extension method, as shown below:
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]; list[n] = value; } }
<方法> How to use:
List<Product> products = GetProducts(); products.Shuffle();
System.Random
System.Security.Cryptography
Thread security considerations
public static void Shuffle<T>(this IList<T> list) { using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider()) { int n = list.Count; while (n > 1) { byte[] box = new byte[1]; do provider.GetBytes(box); while (!(box[0] < (byte)((double)n / 256))); //确保生成的随机数在范围内 int k = (int)(box[0] * (n / 256.0)); T value = list[k]; list[k] = list[n - 1]; list[n - 1] = value; n--; } } }
ThreadSafeRandom
The updated expansion method
public static class ThreadSafeRandom { [ThreadStatic] private static Random Local; public static Random ThisThreadsRandom { get { return Local ?? (Local = new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId))); } } }
<<>
public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } }
The above is the detailed content of How Can I Efficiently Shuffle a Generic List in C#?. For more information, please follow other related articles on the PHP Chinese website!