Add ListExtensions.Shuffle<T>()

Shuffle<T>() returns the source enumerable ordered randomly
This commit is contained in:
Oliver Booth 2019-11-16 02:12:15 +00:00
parent cd04c1b66f
commit 120ea9562e
No known key found for this signature in database
GPG Key ID: 4B0992B2602C3778
1 changed files with 19 additions and 0 deletions

View File

@ -50,5 +50,24 @@
/// <returns>Returns a random element of type <see cref="T"/> from <paramref name="source"/>.</returns> /// <returns>Returns a random element of type <see cref="T"/> from <paramref name="source"/>.</returns>
public static T OneOf<T>(this IList<T> source, Random random) => public static T OneOf<T>(this IList<T> source, Random random) =>
random.OneOf(source); random.OneOf(source);
/// <summary>
/// Shuffles an enumerable.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <returns>Returns <paramref name="source"/> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source) =>
source.Shuffle(new Random());
/// <summary>
/// Shuffles an enumerable.
/// </summary>
/// <typeparam name="T">The collection type.</typeparam>
/// <param name="source">The collection to shuffle.</param>
/// <param name="random">The <see cref="Random"/> instance.</param>
/// <returns>Returns <paramref name="source"/> shuffled.</returns>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random random) =>
source.OrderBy(x => random.Next());
} }
} }