ShuffleExtensions.cs 871 B

12345678910111213141516171819202122232425262728293031
  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. int n = list.Count;
  19. while (n > 1)
  20. {
  21. n--;
  22. int k = _rng.Next(n + 1);
  23. T value = list[k];
  24. list[k] = list[n];
  25. list[n] = value;
  26. }
  27. }
  28. }
  29. }