BLOG.CSHARPHELPER.COM: Make extension methods that randomize arrays and lists in C#
Make extension methods that randomize arrays and lists in C#
The example Randomize the items in an array in C# uses a method to randomize an array. This example converts that method into an extension method and adds another extension method to randomize lists.
Extension methods must be in a public static class. This example creates a RandomizationExtensions class. The class declares a Random object named Rand that is used by all of its methods. (Originally I had each method declare its own Random object. When the program called two methods in rapid succession, however, the Random objects were often initialized to the same state (by default, the object uses the clock to initialize the object) so they often produced identical series of "random" numbers.)
public static class RandomizationExtensions
{
private static Random Rand = new Random();
...
}
The following code shows the extension method that randomizes an array.
// Randomize an array.
public static void Randomize<T>(this T[] items)
{
// For each spot in the array, pick
// a random item to swap into that spot.
for (int i = 0; i < items.Length - 1; i++)
{
int j = Rand.Next(i, items.Length);
T temp = items[i];
items[i] = items[j];
items[j] = temp;
}
}
See the previous example Randomize the items in an array in C# for an explanation.
The following code shows the extension method that randomizes a list.
// Randomize a list.
public static void Randomize<T>(this List<T> items)
{
// Convert into an array.
T[] item_array = items.ToArray();
// Randomize.
item_array.Randomize();
// Copy the items back into the list.
items.Clear();
items.AddRange(item_array);
}
This method uses the list's ToArray method to create an array holding the same items as the list. It then uses the previous Randomize extension method to randomize the array. It then copies the items in the array back into the list.
Comments