ShuffleExtensions.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. namespace MediaBrowser.Common.Extensions
  5. {
  6. /// <summary>
  7. /// Provides <c>Shuffle</c> extensions methods for <see cref="IList{T}" />.
  8. /// </summary>
  9. public static class ShuffleExtensions
  10. {
  11. private static readonly Random _rng = new Random();
  12. /// <summary>
  13. /// Shuffles the items in a list.
  14. /// </summary>
  15. /// <param name="list">The list that should get shuffled.</param>
  16. /// <typeparam name="T">The type.</typeparam>
  17. public static void Shuffle<T>(this IList<T> list)
  18. {
  19. list.Shuffle(_rng);
  20. }
  21. /// <summary>
  22. /// Shuffles the items in a list.
  23. /// </summary>
  24. /// <param name="list">The list that should get shuffled.</param>
  25. /// <param name="rng">The random number generator to use.</param>
  26. /// <typeparam name="T">The type.</typeparam>
  27. public static void Shuffle<T>(this IList<T> list, Random rng)
  28. {
  29. int n = list.Count;
  30. while (n > 1)
  31. {
  32. int k = rng.Next(n--);
  33. T value = list[k];
  34. list[k] = list[n];
  35. list[n] = value;
  36. }
  37. }
  38. }
  39. }