[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

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

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

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.