Title: Make extension methods that randomize arrays and lists in C#
This example uses the techniques described in the post Randomize arrays in C# to make extensions methods that randomize arrays and lists.
Extension methods must be in a public static class. This example creates a RandomizationExtensions class. That class declares a Random object named Rand that is used by all of its methods.
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 for an explanation of how this works.
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 finishes by copying the items in the array back into the list.
The following code shows how the main program uses the extension methods.
private string[] ItemArray;
private List<string> ItemList;
...
ItemArray.Randomize();
ItemList.Randomize();
Easy!
Download the example to experiment with it and to see additional details.
|