ShuffleExtensions.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. n--;
  33. int k = rng.Next(n + 1);
  34. T value = list[k];
  35. list[k] = list[n];
  36. list[n] = value;
  37. }
  38. }
  39. }
  40. }