ShuffleExtensions.cs 1.2 KB

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