diff --git a/README.md b/README.md index e22d745..1560334 100644 --- a/README.md +++ b/README.md @@ -200,12 +200,26 @@ DateTime? ToNullable(this DateTime value); ```csharp /// -/// Randomizes the order of the elements in the collection. +/// Shuffles the elements of the . /// -/// Type of the items in the collection. -/// Collection to randomize. -/// Randomized collection. -IEnumerable Random(this IEnumerable enumerable); +/// The type of the elements in the . +/// The to shuffle. +/// A shuffled . +/// Thrown when is null. +IEnumerable Shuffle(this IEnumerable source); +``` + +--- + +```csharp +/// +/// Gets a random element from the . +/// +/// The type of the elements in the . +/// The to get a random element from. +/// A random element from the . +/// Thrown when is null. +T Random(this IEnumerable enumerable); ``` diff --git a/Sources/EasyExtensions/Extensions/EnumerableExtensions.cs b/Sources/EasyExtensions/Extensions/EnumerableExtensions.cs index 86d390f..87993b4 100644 --- a/Sources/EasyExtensions/Extensions/EnumerableExtensions.cs +++ b/Sources/EasyExtensions/Extensions/EnumerableExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Linq; using System.Collections.Generic; namespace EasyExtensions @@ -9,23 +10,40 @@ namespace EasyExtensions public static class EnumerableExtensions { /// - /// Randomizes the order of the elements in the collection. + /// Shuffles the elements of the . /// - /// Type of the items in the collection. - /// Collection to randomize. - /// Randomized collection. - public static IEnumerable Random(this IEnumerable enumerable) + /// The type of the elements in the . + /// The to shuffle. + /// A shuffled . + /// Thrown when is null. + public static IEnumerable Shuffle(this IEnumerable source) { - Random random = new Random(); - List list = new List(enumerable); - int count = list.Count; - for (int i = 0; i < count; i++) + var random = new Random(); + T[] elements = source.ToArray(); + for (int i = elements.Length - 1; i >= 0; i--) { - int index = random.Next(count); - yield return list[index]; - list.RemoveAt(index); - count--; + int swapIndex = random.Next(i + 1); + yield return elements[swapIndex]; + elements[swapIndex] = elements[i]; } } + + /// + /// Gets a random element from the . + /// + /// The type of the elements in the . + /// The to get a random element from. + /// A random element from the . + /// Thrown when is null. + public static T Random(this IEnumerable enumerable) + { + if (enumerable == null) + { + throw new ArgumentNullException(nameof(enumerable)); + } + var random = new Random(); + var list = enumerable as IList ?? enumerable.ToList(); + return list.Count == 0 ? default! : list[random.Next(0, list.Count)]; + } } }