diff --git a/X10D/src/RandomExtensions.cs b/X10D/src/RandomExtensions.cs index a217c83..fed74fa 100644 --- a/X10D/src/RandomExtensions.cs +++ b/X10D/src/RandomExtensions.cs @@ -9,11 +9,7 @@ namespace X10D /// public static class RandomExtensions { - /// - /// Gets the instance to which other extension methods may refer, when one is - /// needed but not provided. - /// - internal static Random Random { get; } = new Random(); + internal static readonly Random Random = new(); /// /// Returns either or based on the next generation of the current @@ -40,27 +36,23 @@ namespace X10D /// /// Returns a random element from using the instance. /// - /// The collection type. + /// The element type. /// The instance. - /// The collection from which to draw. - /// Returns a random element of type from . - public static T OneOf(this Random random, params T[] source) - { - return source.ToList().OneOf(random); - } - - /// - /// Returns a random element from using the instance. - /// - /// The collection type. - /// The instance. - /// The collection from which to draw. - /// Returns a random element of type from . + /// The source collection from which to draw. + /// A random element of type from . /// - /// or is - /// . + /// is is + /// -or- + /// is . /// - public static T OneOf(this Random random, IList source) + /// + /// + /// var list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + /// var random = new Random(); + /// var number = random.NextFrom(list); + /// + /// + public static T NextFrom(this System.Random random, IEnumerable source) { if (random is null) { @@ -72,7 +64,17 @@ namespace X10D throw new ArgumentNullException(nameof(source)); } - return source[random.Next(source.Count)]; + if (source is T[] array) + { + return array[random.Next(array.Length)]; + } + + if (source is not IReadOnlyList list) + { + list = source.ToList(); + } + + return list[random.Next(list.Count)]; } } }