ShuffleExtensions.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System;
  2. using System.Collections.Generic;
  3. namespace MediaBrowser.Common.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. private static readonly Random _rng = new Random();
  11. /// <summary>
  12. /// Shuffles the items in a list.
  13. /// </summary>
  14. /// <param name="list">The list that should get shuffled.</param>
  15. /// <typeparam name="T">The type.</typeparam>
  16. public static void Shuffle<T>(this IList<T> list)
  17. {
  18. list.Shuffle(_rng);
  19. }
  20. /// <summary>
  21. /// Shuffles the items in a list.
  22. /// </summary>
  23. /// <param name="list">The list that should get shuffled.</param>
  24. /// <param name="rng">The random number generator to use.</param>
  25. /// <typeparam name="T">The type.</typeparam>
  26. public static void Shuffle<T>(this IList<T> list, Random rng)
  27. {
  28. int n = list.Count;
  29. while (n > 1)
  30. {
  31. n--;
  32. int k = rng.Next(n + 1);
  33. T value = list[k];
  34. list[k] = list[n];
  35. list[n] = value;
  36. }
  37. }
  38. }
  39. }