Make extension methods that randomize arrays and lists in C#

[randomize arrays and lists]

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();


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in algorithms, extension methods, mathematics and tagged , , , , , , , , , , , . Bookmark the permalink.

One Response to Make extension methods that randomize arrays and lists in C#

  1. Sinan says:

    An extension method has simplified calling syntax. It represents static methods as instance methods. An extension method uses the this-keyword in its parameter list. It must be located in a static class.

Leave a Reply

Your email address will not be published. Required fields are marked *