# VBForums CodeBank > CodeBank - C# >  Useful Extension Methods

## jmcilhinney

VB version here.

This is a library of extension methods I've been building to make various things easier and or cleaner in code.  The solution was created in VS 2017 and all initial projects target .NET 4.7.1.  The solution contains C# and VB projects and I will provide some extra explanation and examples of the C# code here.  The TestBed projects are WinForms and are intended to provide tests for pretty much all the included extensions.  They are currently incomplete but I will replace the attachment when I have finished them.

You can build the solution and use the compiled libraries with your own applications, or I'm happy for anyone to copy whichever parts of the code they find useful and use them directly in their own projects.  While I don't require explicit credit, I also require that you don't try to take explicit credit for the code.

EDIT 23 April, 2018: Improved TestBed projects.  Removed ParamArray from 'weightings' parameters of existing RandomExtensions.NextWithWeighting overloads.  Added new overloads of RandomExtensions.NextWithWeighting enabling implicitly specifying weightings for some possible outcomes.

EDIT 23 April, 2018: Improved TestBed projects.  Fixed bug in Random project.  Fixed bug in VB Numerics project.

EDIT 3 May, 2018: Changed Image project to Drawing and added DrawCircle and DrawTriangle extensions for Graphics class.  Add ToLines method to String extensions.

EDIT 19 May, 2018:  Added ArrayExtensions to Enumerable project.  Added unit test projects.

----------


## jmcilhinney

csharp Code:
// Saves an <see cref="Image"/> to an array of <see cref="byte"/>'s.public static byte[] ToBytes(this Image source)// Saves an <see cref="Image"/> to an array of <see cref="byte"/>'s in the specified format.public static byte[] ToBytes(this Image source, ImageFormat format)// Saves an <see cref="Image"/> to an array of <see cref="byte"/>'s, with the specified encoder and image-encoder parameters.public static byte[] ToBytes(this Image source, ImageCodecInfo encoder, EncoderParameters encoderParams)

csharp Code:
// Converts an array of <see cref="byte"/> containing image data into an <see cref="Image"/> object.public static Image ToImage(this IEnumerable<byte> source)
The methods in the Image project are basically about converting between an Image object and a Byte array and vice versa.  These operations are required when saving and loading images in databases, as well as in other situations.

csharp Code:
using System.Drawing;using System.Drawing.Imaging;using System.IO; namespace Wunnell.Extensions{    /// <summary>    /// Contains methods that extend the <see cref="Image"/> class.    /// </summary>    public static class ImageExtensions    {        /// <summary>        /// Saves an <see cref="Image"/> to an array of <see cref="byte"/>'s.        /// </summary>        /// <param name="source">        /// The inoput image.        /// </param>        /// <returns>        /// An array containing the image data.        /// </returns>        public static byte[] ToBytes(this Image source)        {            return source.ToBytes(source.RawFormat);        }         /// <summary>        /// Saves an <see cref="Image"/> to an array of <see cref="byte"/>'s in the specified format.        /// </summary>        /// <param name="source">        /// The inoput image.        /// </param>        /// <param name="format">        /// The <see cref="ImageFormat"/> for this <see cref="Image"/>.        /// </param>        /// <returns>        /// An array containing the image data.        /// </returns>        public static byte[] ToBytes(this Image source, ImageFormat format)        {            using (var stream = new MemoryStream())            {                source.Save(stream, format);                 return stream.ToArray();            }        }         /// <summary>        /// Saves an <see cref="Image"/> to an array of <see cref="byte"/>'s, with the specified encoder and image-encoder parameters.        /// </summary>        /// <param name="source">        /// The inoput image.        /// </param>        /// <param name="encoder"></param>        /// <param name="encoderParams"></param>        /// <returns>        /// An array containing the image data.        /// </returns>        public static byte[] ToBytes(this Image source, ImageCodecInfo encoder, EncoderParameters encoderParams)        {            using (var stream = new MemoryStream())            {                source.Save(stream, encoder, encoderParams);                 return stream.ToArray();            }        }    }}

csharp Code:
using System.Collections.Generic;using System.Drawing;using System.IO;using System.Linq; namespace Wunnell.Extensions{    /// <summary>    /// Contains methods that extend the <see cref="IEnumerable{T}"/> interface.    /// </summary>    public static class EnumerableExtensions    {        /// <summary>        /// Converts an array of <see cref="byte"/> containing image data into an <see cref="Image"/> object.        /// </summary>        /// <param name="source">        /// The input byte array.        /// </param>        /// <returns>        /// The image represented by the input data.        /// </returns>        public static Image ToImage(this IEnumerable<byte> source)        {            using (var stream = new MemoryStream(source.ToArray()))            {                return Image.FromStream(stream);            }        }    }}
These methods simply encapsulate the use of a MemoryStream go between an Image and a Byte array or vice versa.  Saving an Image to a database might look like this:


```
using (var connection = new SqlConnection("connection string here"))
using (var command = new SqlCommand("UPDATE MyTable SET Picture = @Picture WHERE Id = @Id", connection))
{
    command.Parameters.Add("@Picture", SqlDbType.VarBinary, -1).Value = pictureBox1.Image.ToBytes();
    command.Parameters.Add("@Id", SqlDbType.Int).Value = 1;

    connection.Open();
    command.ExecuteNonQuery();
}
```

while retrieving that Image might look like this:


```
using (var connection = new SqlConnection("connection string here"))
using (var command = new SqlCommand("SELECT Picture FROM MyTable WHERE Id = @Id", connection))
{
    command.Parameters.Add("@Id", SqlDbType.Int).Value = 1;

    connection.Open();

    var data = (byte[]) command.ExecuteScalar();

    pictureBox1.Image = data.ToImage();
}
```

The three overloads of ToBytes correlate to the three overloads of Image.Save that have a first parameter of type String, where one saves using the raw format of the Image object, one takes a format to save in and the third takes an encoder and encoding parameters.

----------


## jmcilhinney

csharp Code:
// Returns a non-negative random integer that is less than the specified maximum where each value in that range has a weighted probability.public static int NextWithWeighting(this Random source,                                    int maxValue,                                    int[] weightings)// Returns a random integer that is within a specified range where each value in that range has a weighted probability.public static int NextWithWeighting(this Random source,                                    int minValue,                                    int maxValue,                                    int[] weightings)// Returns a non-negative random integer that is less than the specified maximum where each value in that range has a weighted probability.public static int NextWithWeighting(this Random source,                                    int maxValue,                                    IDictionary<int,int> weightings)// Returns a random integer that is within a specified range where each value in that range has a weighted probability.public static int NextWithWeighting(this Random source,                                    int minValue,                                    int maxValue,                                    IDictionary<int, int> weightings)// Returns a non-negative random integer that is less than the specified maximum where each value in that range has a weighted probability.public static int NextWithWeighting(this Random source,                                    int maxValue,                                    IDictionary<int, int> weightings,                                    int defaultWeighting)// Returns a random integer that is within a specified range where each value in that range has a weighted probability.public static int NextWithWeighting(this Random source,                                    int minValue,                                    int maxValue,                                    IDictionary<int, int> weightings,                                    int defaultWeighting)
The methods in the Random project enable you to generate a random number in a range where each number can have a different likelihood of being generated.

csharp Code:
using System;using System.Collections.Generic;using System.Linq; namespace Wunnell.Extensions{    /// <summary>    /// Contains methods that extend the <see cref="Random"/> class.    /// </summary>    public static class RandomExtensions    {        private const int DEFAULT_WEIGHTING = 1;         /// <summary>        /// Returns a non-negative random integer that is less than the specified maximum where each value in that range has a weighted probability.        /// </summary>        /// <param name="source">        /// The <see cref="Random"/> object to use to generate the number.        /// </param>        /// <param name="maxValue">        /// The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.        /// </param>        /// <param name="weightings">        /// The weightings for each of the possible outcomes.        /// </param>        /// <returns>        /// A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned.        /// </returns>        /// <remarks>        /// A non-negative weighting must be provided for each possible outcome.  Weightings are a proportion of the total of all weightings.  They are not percentages.        /// For instance, if there are three possible outcomes and the weightings are 1, 2 and 3 then the first outcome will result about 1/6 of the time, the second outcome will result about 1/3 of the time and the third outcome will result about 1/2 of the time.        /// </remarks>        public static int NextWithWeighting(this Random source,                                            int maxValue,                                            int[] weightings)        {            return source.NextWithWeighting(0, maxValue, weightings);        }         /// <summary>        /// Returns a random integer that is within a specified range where each value in that range has a weighted probability.        /// </summary>        /// <param name="source">        /// The <see cref="Random"/> object to use to generate the number.        /// </param>        /// <param name="minValue">        /// The inclusive lower bound of the random number returned.        /// </param>        /// <param name="maxValue">        /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.        /// </param>        /// <param name="weightings">        /// The weightings for each of the possible outcomes.        /// </param>        /// <returns>        /// A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.        /// </returns>        /// <remarks>        /// A non-negative weighting must be provided for each possible outcome.  Weightings are a proportion of the total of all weightings.  They are not percentages.        /// For instance, if there are three possible outcomes and the weightings are 1, 2 and 3 then the first outcome will result about 1/6 of the time, the second outcome will result about 1/3 of the time and the third outcome will result about 1/2 of the time.        /// </remarks>        public static int NextWithWeighting(this Random source,                                            int minValue,                                            int maxValue,                                            int[] weightings)        {            if (minValue > maxValue)            {                throw new ArgumentOutOfRangeException($"'{nameof(minValue)}' cannot be greater than {nameof(maxValue)}.", nameof(minValue));            }             if (maxValue > minValue && weightings.Length != maxValue - minValue)            {                throw new ArgumentException("A weighting must be provided for all possible outcomes.", nameof(weightings));            }             if (weightings.Any(n => n < 0))            {                throw new ArgumentException("All weightings must be greater than zero.", nameof(weightings));            }             int totalWeightings;             try            {                totalWeightings = weightings.Sum();            }            catch (OverflowException e)            {                throw new ArgumentException("The sum of all weightings must not be greater than Int32.MaxValue.", e);            }             if (totalWeightings == 0)            {                throw new ArgumentException("The sum of all weightings must be greater than zero.", nameof(weightings));            }             if (minValue == maxValue || minValue == maxValue + 1)            {                // There is only one possible value.                return minValue;            }             // Generate a number in the range 0 to 1 less than the total weightings.            var number = source.Next(totalWeightings);             var runningWeighting = 0;             // For each weighting, check whether the number generated falls in that interval.            for (var i = 0; i < weightings.Length; i++)            {                // Sum the weightings so far.                // E.g. if the weightings are 10, 20, 30 and 40 then the running weighting for each iteration will be:                // i = 0: runningWeighting = 0 + 10 = 10                // i = 1: runningWeighting = 10 + 20 = 30                // i = 2: runningWeighting = 30 + 30 = 60                // i = 3: runningWeighting = 60 + 40 = 100                runningWeighting += weightings[i];                 // There is no interval until the running weighting is greater than zero.                if (runningWeighting > 0 && number < runningWeighting)                {                    // The number generated falls within the current weighting interval so get the value from the original range that corresponds to that interval.                    return minValue + i;                }            }             // If we end up here then something was wrong with the interval and/or the weightings.            // The validation at the top of the method should ensure that such cases are always caught first.            throw new Exception("An unexpected error occurred.");        }         /// <summary>        /// Returns a non-negative random integer that is less than the specified maximum where each value in that range has a weighted probability.        /// </summary>        /// <param name="source">        /// The <see cref="Random"/> object to use to generate the number.        /// </param>        /// <param name="maxValue">        /// The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.        /// </param>        /// <param name="weightings">        /// A dictionary containing the weightings for some or all of the possible outcomes, where the keys are the possible outcomes and the values are the weightings.        /// </param>        /// <returns>        /// A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned.        /// </returns>        /// <remarks>        /// A weighting of 1 is used for any values for which a weighting is not explicitly provided.  Weightings are a proportion of the total of all weightings.  They are not percentages.        /// For instance, if there are three possible outcomes and the weightings are 1, 2 and 3 then the first outcome will result in about 1/6 of the time, the second outcome will result about 1/3 of the time and the third outcome will result about 1/2 of the time.        /// </remarks>        public static int NextWithWeighting(this Random source,                                            int maxValue,                                            IDictionary<int,int> weightings)        {            return source.NextWithWeighting(0, maxValue, weightings);        }         /// <summary>        /// Returns a random integer that is within a specified range where each value in that range has a weighted probability.        /// </summary>        /// <param name="source">        /// The <see cref="Random"/> object to use to generate the number.        /// </param>        /// <param name="minValue">        /// The inclusive lower bound of the random number returned.        /// </param>        /// <param name="maxValue">        /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.        /// </param>        /// <param name="weightings">        /// A dictionary containing the weightings for some or all of the possible outcomes, where the keys are the possible outcomes and the values are the weightings.        /// </param>        /// <returns>        /// A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.        /// </returns>        /// <remarks>        /// A weighting of 1 is used for any values for which a weighting is not explicitly provided.  Weightings are a proportion of the total of all weightings.  They are not percentages.        /// For instance, if there are three possible outcomes and the weightings are 1, 2 and 3 then the first outcome will result in about 1/6 of the time, the second outcome will result about 1/3 of the time and the third outcome will result about 1/2 of the time.        /// </remarks>        public static int NextWithWeighting(this Random source,                                            int minValue,                                            int maxValue,                                            IDictionary<int, int> weightings)        {            return source.NextWithWeighting(minValue, maxValue, weightings, DEFAULT_WEIGHTING);        }         /// <summary>        /// Returns a non-negative random integer that is less than the specified maximum where each value in that range has a weighted probability.        /// </summary>        /// <param name="source">        /// The <see cref="Random"/> object to use to generate the number.        /// </param>        /// <param name="maxValue">        /// The exclusive upper bound of the random number to be generated. maxValue must be greater than or equal to 0.        /// </param>        /// <param name="weightings">        /// A dictionary containing the weightings for some or all of the possible outcomes, where the keys are the possible outcomes and the values are the weightings.        /// </param>        /// <param name="defaultWeighting">        /// Thw weighting to be used for those values for which one is not explicitly provided.        /// </param>        /// <returns>        /// A 32-bit signed integer that is greater than or equal to 0, and less than maxValue; that is, the range of return values ordinarily includes 0 but not maxValue. However, if maxValue equals 0, maxValue is returned.        /// </returns>        /// <remarks>        /// Weightings are a proportion of the total of all weightings.  They are not percentages.        /// For instance, if there are three possible outcomes and the weightings are 1, 2 and 3 then the first outcome will result in about 1/6 of the time, the second outcome will result about 1/3 of the time and the third outcome will result about 1/2 of the time.        /// </remarks>        public static int NextWithWeighting(this Random source,                                            int maxValue,                                            IDictionary<int, int> weightings,                                            int defaultWeighting)        {            return source.NextWithWeighting(0, maxValue, weightings, defaultWeighting);        }         /// <summary>        /// Returns a random integer that is within a specified range where each value in that range has a weighted probability.        /// </summary>        /// <param name="source">        /// The <see cref="Random"/> object to use to generate the number.        /// </param>        /// <param name="minValue">        /// The inclusive lower bound of the random number returned.        /// </param>        /// <param name="maxValue">        /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal to minValue.        /// </param>        /// <param name="weightings">        /// A dictionary containing the weightings for some or all of the possible outcomes, where the keys are the possible outcomes and the values are the weightings.        /// </param>        /// <param name="defaultWeighting">        /// Thw weighting to be used for those values for which one is not explicitly provided.        /// </param>        /// <returns>        /// A 32-bit signed integer greater than or equal to minValue and less than maxValue; that is, the range of return values includes minValue but not maxValue. If minValue equals maxValue, minValue is returned.        /// </returns>        /// <remarks>        /// Weightings are a proportion of the total of all weightings.  They are not percentages.        /// For instance, if there are three possible outcomes and the weightings are 1, 2 and 3 then the first outcome will result in about 1/6 of the time, the second outcome will result about 1/3 of the time and the third outcome will result about 1/2 of the time.        /// </remarks>        public static int NextWithWeighting(this Random source,                                            int minValue,                                            int maxValue,                                            IDictionary<int, int> weightings,                                            int defaultWeighting)        {            if (minValue > maxValue)            {                throw new ArgumentOutOfRangeException($"'{nameof(minValue)}' cannot be greater than {nameof(maxValue)}.", nameof(minValue));            }             if (weightings.Keys.Any(k => k < minValue ||                                         minValue == maxValue && k > maxValue ||                                         minValue < maxValue && k >= maxValue))            {                throw new ArgumentException("Weightings cannot be provided for values outside the specified range.");            }             if (defaultWeighting < 0)            {                throw new ArgumentOutOfRangeException(nameof(defaultWeighting), defaultWeighting, "Value cannot be less than zero.");            }             var allWeightings = new List<int>                                {                                    weightings.TryGetValue(minValue, out var weighting)                                        ? weighting                                        : defaultWeighting                                };             for (var i = minValue + 1; i < maxValue; i++)            {                allWeightings.Add(weightings.TryGetValue(i, out weighting)                                      ? weighting                                      : defaultWeighting);            }             return source.NextWithWeighting(minValue, maxValue, allWeightings.ToArray());        }    }}
The overloads of NextWithWeighting correspond to the overloads of Random.Next that have parameters.  Like those Next overloads, the 'maxValue' parameter is exclusive while the 'minValue' parameter is inclusive.  NextWithWeighting requires that a weighting is provided for every possible outcome.  I plan to add overloads that allow you to provide weightings for just specific values and have a default for everything else.

As an example, the following code generates random numbers that are greater than or equal to zero and less than 4.  The possible outcomes of 0, 1, 2 and 3 have weightings of 1, 2, 3 and 4 respectively.  That means that, for every 1 time that value 0 is generated, the value 1 should be generated twice, the value 2 should be generated three times and the value 3 should be generated four times.


```
var rng = new Random();
var results = new Dictionary<int, int> {{0, 0}, {1, 0}, {2, 0}, {3, 0}};

for (var i = 0; i < 1000; i++)
{
    var number = rng.NextWithWeighting(4, new[] {1, 2, 3, 4});

    results[number]++;
}

foreach (var kvp in results)
{
    Console.WriteLine("{0} was generated {1} times.", kvp.Key, kvp.Value);
}
```

If you run that code multiple times and check the output, you'll see that the specific results will vary but they are close to those proportions each time, i.e. 0 is generated about 100 out of 1000 times, 1 is generated about 200 times, 2 is generated about 300 times and 3 is generated about 400 times.

The following code is similar but specifies a lower bound for the range and less regular weightings:


```
var rng = new Random();
var results = new Dictionary<int, int>();

for (var i = 8; i < 14; i++)
{
    results.Add(i, 0);
}

var weightings = new[] {11, 5, 3, 21, 65, 26};

for (var i = 0; i < weightings.Sum() * 100; i++)
{
    var number = rng.NextWithWeighting(8, 14, weightings);

    results[number]++;
}

foreach (var kvp in results)
{
    Console.WriteLine("{0} was generated {1} times.", kvp.Key, kvp.Value);
}
```

Again, if you run that code multiple times, you should see that the proportions in which the values are generated is always approximately the same as specified by the weightings.

Note that the weightings are not percentages and so they do not have to sum to 100.  They are simply relative proportions.  That means that weightings of 1, 2 and 3 are perfectly equivalent to weightings of 347, 694 and 1041.

----------


## jmcilhinney

csharp Code:
// Gets a value indicating whether a <see cref="DateTime"/> value represents a week day.public static bool IsWeekDay(this DateTime source)// Returns a new <see cref="DateTime"/> that adds the specified number of week days to a specified value.public static DateTime AddWeekDays(this DateTime source, double value)
The methods in the DateTime project allow you to easily add a number of days to a DateTime while ignoring weekends.

csharp Code:
using System; namespace Wunnell.Extensions{    /// <summary>    /// Contains methods that extend the <see cref="DateTime"/> structure.    /// </summary>    public static class DateTimeExtensions    {        /// <summary>        /// Gets a value indicating whether a <see cref="DateTime"/> value represents a week day.        /// </summary>        /// <param name="source">        /// The input <see cref="DateTime"/>, which acts as the <b>this</b> instance for the extension method.        /// </param>        /// <returns>        /// <b>true</b> if the represents a week day; otherwise <b>false</b>.        /// </returns>        /// <remarks>        /// All days other than Saturday and Sunday are considered week days.        /// </remarks>        public static bool IsWeekDay(this DateTime source)        {            return source.DayOfWeek != DayOfWeek.Saturday &&                   source.DayOfWeek != DayOfWeek.Sunday;        }         /// <summary>        /// Returns a new <see cref="DateTime"/> that adds the specified number of week days to a specified value.        /// </summary>        /// <param name="source">        /// The input <see cref="DateTime"/>, which acts as the <b>this</b> instance for the extension method.        /// </param>        /// <param name="value">        /// A number of whole and fractional days. The <i>value</i> parameter can be negative or positive.        /// </param>        /// <returns>        /// An object whose value is the sum of the date and time represented by this instance and the number of week days represented by <i>value</i>.        /// </returns>        /// <remarks>        /// All days other than Saturday and Sunday are considered week days.        /// </remarks>        public static DateTime AddWeekDays(this DateTime source, double value)        {            // A unit will be +/- 1 day.            var unit = Math.Sign(value) * 1.0;             // Start increasing the date by units from the initial date.            var result = source;             // When testing for zero, allow a margin for precision error.            while (!value.IsEquivalentTo(0.0, 0.0001))            {                if (Math.Abs(value) < 1.0)                {                    // There is less than one full day to add so we need to see whether adding it will take us past midnight.                    var temp = result.AddDays(value);                     if (temp.Date == result.Date || temp.IsWeekDay())                    {                        // Adding the partial day did not take us into a weekend day so we're done.                        result = temp;                        value = 0.0;                    }                    else                    {                        // Adding the partial day took us into a weekend day so we need to add another day.                        result = result.AddDays(unit);                    }                }                else                {                    // Add a single day.                    result = result.AddDays(unit);                     if (result.IsWeekDay())                    {                        // Adding a day did not take us into a weekend day so we can reduce the remaining value to add.                        value -= unit;                    }                }            }             return result;        }    }}
The AddWeekDays method works in the same way as the DateTime.AddDays method in that it can take a positive or negative, whole or fractional number of days and create a new DateTime by adding that number of days to the original Date.  The following code compares the two methods:


```
var startDate = new DateTime(2018, 4, 19, 11, 0, 0);

for (var i = 0.5; i <= 10.0; i += 0.5)
{
    var endDate = startDate.AddDays(i);

    Console.WriteLine("{0:ddd, d MMM yyyy h:mm tt} + {1:0.0} days =      {2:ddd, d MMM yyyy h:mm tt}", startDate, i, endDate);

    endDate = startDate.AddWeekDays(i);

    Console.WriteLine("{0:ddd, d MMM yyyy h:mm tt} + {1:0.0} week days = {2:ddd, d MMM yyyy h:mm tt}", startDate, i, endDate);
}
```

That code produces the following output:


```
Thu, 19 Apr 2018 11:00 AM + 0.5 days =      Thu, 19 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 0.5 week days = Thu, 19 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 1.0 days =      Fri, 20 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 1.0 week days = Fri, 20 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 1.5 days =      Fri, 20 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 1.5 week days = Fri, 20 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 2.0 days =      Sat, 21 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 2.0 week days = Mon, 23 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 2.5 days =      Sat, 21 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 2.5 week days = Mon, 23 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 3.0 days =      Sun, 22 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 3.0 week days = Tue, 24 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 3.5 days =      Sun, 22 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 3.5 week days = Tue, 24 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 4.0 days =      Mon, 23 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 4.0 week days = Wed, 25 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 4.5 days =      Mon, 23 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 4.5 week days = Wed, 25 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 5.0 days =      Tue, 24 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 5.0 week days = Thu, 26 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 5.5 days =      Tue, 24 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 5.5 week days = Thu, 26 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 6.0 days =      Wed, 25 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 6.0 week days = Fri, 27 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 6.5 days =      Wed, 25 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 6.5 week days = Fri, 27 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 7.0 days =      Thu, 26 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 7.0 week days = Mon, 30 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 7.5 days =      Thu, 26 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 7.5 week days = Mon, 30 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 8.0 days =      Fri, 27 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 8.0 week days = Tue, 1 May 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 8.5 days =      Fri, 27 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 8.5 week days = Tue, 1 May 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 9.0 days =      Sat, 28 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 9.0 week days = Wed, 2 May 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 9.5 days =      Sat, 28 Apr 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 9.5 week days = Wed, 2 May 2018 11:00 PM
Thu, 19 Apr 2018 11:00 AM + 10.0 days =      Sun, 29 Apr 2018 11:00 AM
Thu, 19 Apr 2018 11:00 AM + 10.0 week days = Thu, 3 May 2018 11:00 AM
```

----------


## jmcilhinney

csharp Code:
// Randomises the items in an enumerable list.public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
The method in the Enumerable project allows you to order an enumerable list of items randomly.

csharp Code:
using System;
using System.Collections.Generic;
using System.Linq;
 namespace Wunnell.Extensions
{
    /// <summary>
    /// Contains methods that extend the <see cref="IEnumerable{T}"/> interface.
    /// </summary>
    public static class EnumerableExtensions
    {
        /// <summary>
        /// A random number generator.
        /// </summary>
        private static Random rng;
         /// <summary>
        /// Randomises the items in an enumerable list.
        /// </summary>
        /// <typeparam name="T">
        /// The type of the items in the list.
        /// </typeparam>
        /// <param name="source">
        /// The input list.
        /// </param>
        /// <returns>
        /// The items from the input list in random order.
        /// </returns>
        public static IEnumerable<T> Randomize<T>(this IEnumerable<T> source)
        {
            EnsureRandomInitialized();
             return source.OrderBy(o => rng.NextDouble());
        }
         /// <summary>
        /// Initialises the random number generator if it is not already.
        /// </summary>
        private static void EnsureRandomInitialized()
        {
            rng = rng ?? new Random();
        }
    }
}
Note that this method cannot be used to randomise an array or collection in-place.  If called on an object implementing IList(Of T), it doesn't not affect the order of the items in that list, but exposes those items as an enumerable list in random order.  That list can be enumerated directly or used as the source for another array or collection.  For example, you could use this method to simulate a lottery draw like so:


```
var allNumbers = Enumerable.Range(1, 40);
var selectedNumbers = allNumbers.Randomize().Take(6);

Console.WriteLine("Your winning lottery numbers tonight are: " + string.Join(", ", selectedNumbers));
```

You might also use this method to shuffle a deck of cards:


```
var values = new[] {"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
var suits = new[] {"Hearts", "Clubs", "Diamonds", "Spades"};
var allCards = from value in values
               from suit in suits
               select $"{value} of {suit}";
var deck = new Stack<string>(allCards.Randomize());
var hand = new List<string>();

for (var i = 0; i < 5; i++)
{
    hand.Add(deck.Pop());
}

Console.WriteLine("Your hand contains: " + string.Join(", ", hand));
```

----------


## jmcilhinney

Updated attachment.  See edit to post #1.

----------


## jmcilhinney

Updated attachment. See edit to post #1.

----------

