From 34cead7e0216bac9aeed0c589c9a6b6b171b050c Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 7 Mar 2021 14:20:30 +0000 Subject: [PATCH] Add Random.NextString(IReadOnlyList, int) --- X10D/src/RandomExtensions/RandomExtensions.cs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/X10D/src/RandomExtensions/RandomExtensions.cs b/X10D/src/RandomExtensions/RandomExtensions.cs index 4da372c..4d7eaa0 100644 --- a/X10D/src/RandomExtensions/RandomExtensions.cs +++ b/X10D/src/RandomExtensions/RandomExtensions.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text; namespace X10D.RandomExtensions { @@ -97,5 +98,57 @@ namespace X10D.RandomExtensions return list[random.Next(list.Count)]; } + + /// + /// Returns a new string of a specified length which is composed of specified characters. + /// + /// The instance. + /// The source collection of characters to poll. + /// The length of the new string to generate. + /// + /// A whose length is equal to that of , composed of characters + /// specified by the characters in . + /// + /// + /// is . + /// -or- + /// is . + /// + /// is less than 0. + public static string NextString(this Random random, IReadOnlyList source, int length) + { + if (random is null) + { + throw new ArgumentNullException(nameof(random)); + } + + if (source is null) + { + throw new ArgumentNullException(nameof(source)); + } + + if (length < 0) + { + throw new ArgumentOutOfRangeException(nameof(length), ExceptionMessages.LengthMustBePositiveValue); + } + + if (length == 0) + { + return string.Empty; + } + + if (length == 1) + { + return source[random.Next(0, source.Count)].ToString(); + } + + var builder = new StringBuilder(length); + for (var i = 0; i < length; i++) + { + builder.Append(source[random.Next(0, source.Count)]); + } + + return builder.ToString(); + } } }