Click here to Skip to main content
15,881,881 members
Articles / Programming Languages / C#

Adding Random Functionality to Generic Lists using Extension Methods

Rate me:
Please Sign up or sign in to vote.
3.40/5 (3 votes)
29 Apr 2009CPOL2 min read 24.5K   170   7   4
Extends IList to include a shuffle method and a 'select an element at random' method.

Introduction

The .NET Framework provides a vast array of functionality for manipulating lists. However one of the requirements that frequently crops up is having the ability to reorder a list into a random sequence or select a random element from a list. Both are relatively straightforward and can be achieved effectively with a couple of extension methods on IList<T> meaning they'll be available for use on any List<T> or ObservableCollection<T> as well as any classes that derive from them.

Note: This article has been updated, scroll to the bottom to see the history.

Selecting a Random Element

A method to select an element at random can be implemented using an extension method but must be on a static class.

Things to note are that Random.Next returns a value between 0 and list.Count – 1, i.e. less than the maximum specified (separately, I actually have an extension method for Random that can return a value using inclusive parameter values). The statement default(T) is used because value types cannot be set to null (think int as opposed to int?).

C#
private static Random random = new Random();
 
public static T GetRandom<T>(this IList<T> list)
{
  if (list.Count == 0)
  {
    return default(T);
  }
  return list[random.Next(0, list.Count)];
}

Reordering a List

Now we have a flavour for Random how about manipulating the elements within a list. Again an extension method provides a neat way to do this:

C#
public static void Shuffle <T>(this IList <T> list) 
{ 
  if (list.Count <= 1) 
  { 
    return; // nothing to do 
  } 
  
  for (int i = 0; i < list.Count; i++) 
  { 
    int newIndex = random.Next(0, list.Count); 
    
    // swap the two elements over 
    T x = list[i]; 
    list[i] = list[newIndex]; 
    list[newIndex] = x; 
  }
}

This works by looping over each element in the list and swapping it with another element at a randomly selected position. Note that like many things, this code will work fine when lists are reasonably small but it is outside the scope of this article to discuss optimisations for manipulating lists.

Conclusion

These methods are just two examples of how lists can be extended to include functionality that produces randomised output and by putting them onto a base generic interface that allows for reuse over a great many classes.

History

  • Version 1.0
    • Initial release
  • Version 1.1
    • Updated shuffle algorithm to be properly random
    • Improved sample

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Play.com
United Kingdom United Kingdom
Hi, my name's Andy Wilson and I live in Cambridge, UK where I work as a Senior C# Software Developer.

Comments and Discussions

 
Generalincorrect shuffle and solution Pin
jpmik29-Apr-09 23:46
jpmik29-Apr-09 23:46 
GeneralMinor flaw Pin
User 304249828-Apr-09 6:41
User 304249828-Apr-09 6:41 
GeneralRe: Minor flaw Pin
andywilsonuk28-Apr-09 22:54
andywilsonuk28-Apr-09 22:54 
GeneralRe: Minor flaw Pin
Izzet Kerem Kusmezer5-May-09 1:00
Izzet Kerem Kusmezer5-May-09 1:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.