diff options
Diffstat (limited to 'src/Jellyfin.Extensions/ShuffleExtensions.cs')
| -rw-r--r-- | src/Jellyfin.Extensions/ShuffleExtensions.cs | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/Jellyfin.Extensions/ShuffleExtensions.cs b/src/Jellyfin.Extensions/ShuffleExtensions.cs new file mode 100644 index 000000000..4e481983f --- /dev/null +++ b/src/Jellyfin.Extensions/ShuffleExtensions.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; + +namespace Jellyfin.Extensions +{ + /// <summary> + /// Provides <c>Shuffle</c> extensions methods for <see cref="IList{T}" />. + /// </summary> + public static class ShuffleExtensions + { + private static readonly Random _rng = new Random(); + + /// <summary> + /// Shuffles the items in a list. + /// </summary> + /// <param name="list">The list that should get shuffled.</param> + /// <typeparam name="T">The type.</typeparam> + public static void Shuffle<T>(this IList<T> list) + { + list.Shuffle(_rng); + } + + /// <summary> + /// Shuffles the items in a list. + /// </summary> + /// <param name="list">The list that should get shuffled.</param> + /// <param name="rng">The random number generator to use.</param> + /// <typeparam name="T">The type.</typeparam> + public static void Shuffle<T>(this IList<T> list, Random rng) + { + int n = list.Count; + while (n > 1) + { + int k = rng.Next(n--); + T value = list[k]; + list[k] = list[n]; + list[n] = value; + } + } + } +} |
