Make extension methods that pick random items from arrays or lists in C#

[random items]

This example uses a simple but useful technique to let you pick random items from arrays and lists. The following code defines RandomElement extension methods that pick random items.

public static class ArrayExtensions
{
    // The random number generator.
    private static Random Rand = new Random();

    // Return a random item from an array.
    public static T RandomElement<T>(this T[] items)
    {
        // Return a random item.
        return items[Rand.Next(0, items.Length)];
    }

    // Return a random item from a list.
    public static T RandomElement<T>(this List<T> items)
    {
        // Return a random item.
        return items[Rand.Next(0, items.Count)];
    }
}

These methods simply use the Random class to pick a random index in the array or list. They then return the element with that index.

Using the methods is easy. You simply invoke an array or list’s RandomElement method. The example program uses the following code to create an array and a list holding animal names.

// The values from which to pick randomly.
private string[] ArrayValues =
{
    "Ape",
    "Bear",
    "Cat",
    "Dog",
    "Elf",
    "Frog",
    "Giraffe",
};
private List<string> ListValues;

// Initialize the list from the array.
private void Form1_Load(object sender, EventArgs e)
{
    ListValues = new List<string>();
    foreach (string value in ArrayValues)
        ListValues.Add(value);

    lstItems.DataSource = ArrayValues;
}

When you click the Pick button, the following code displays random items chosen from the array and list.

// Pick a random value.
private void btnPick_Click(object sender, EventArgs e)
{
    txtFromArray.Text = ArrayValues.RandomElement();
    txtFromList.Text = ListValues.RandomElement();
}

These statements simply invoke the array and list RandomElement methods to pick random items.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in arrays, extension methods, lists and tagged , , , , , , , , , . Bookmark the permalink.

One Response to Make extension methods that pick random items from arrays or lists in C#

  1. Pingback: Make a Shakespeare insult generator in C# - C# HelperC# Helper

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.