Click here to Skip to main content
Click here to Skip to main content

Adding Random Functionality to Generic Lists using Extension Methods

, 29 Apr 2009
Rate this:
Please Sign up or sign in to vote.
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?).

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:

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)

About the Author

andywilsonuk
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 PinmemberJean-Paul Mikkers29-Apr-09 23:46 
GeneralMinor flaw PinmemberJoe Enos28-Apr-09 6:41 
GeneralRe: Minor flaw Pinmemberdevwilson28-Apr-09 22:54 
GeneralRe: Minor flaw PinmemberIzzet Kerem Kusmezer5-May-09 1:00 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 29 Apr 2009
Article Copyright 2009 by andywilsonuk
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid