ShuffleExtensions.cs 1.2 KB

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