PDA

Click to See Complete Forum and Search --> : (.NET 3.5) Randomise a List of Items


jmcilhinney
Sep 29th, 2009, 08:25 AM
VB version here (http://www.vbforums.com/showthread.php?t=585813).

The following is an extension method for getting the contents of any IEnumerable(Of T) object, e.g. an array or List(Of T), in random order:using System;
using System.Collections.Generic;
using System.Linq;

public static class Enumerable
{
public static IEnumerable<T> Randomise<T>(this IEnumerable<T> items)
{
T[] result = null;

if (items != null)
{
var rng = new Random();

result = (from item in items
orderby rng.NextDouble()
select item).ToArray();
}

return result;
}
}Note that it obeys the rules for extension methods, i.e. it's a member of a static class and the first argument is declared with the 'this' keyword. You might use it something like this:int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

foreach (var number in numbers.Randomise())
{
MessageBox.Show(number.ToString());
}Try running that repeatedly and you'll get a different order each time.

Note that you could write a regular method that does the same thing in earlier versions.

jmcilhinney
Sep 29th, 2009, 08:56 PM
Note that I have simplified the code a little from the original. The new code will not throw an exception if you call it on a null reference but it will return a null reference. As such, an exception will be thrown if you try to enumerate the result, which did not happen with the old code. You could easily adjust the code to return an empty array if a null reference is passed in to avoid that if you think it's appropriate.

DeanMc
Oct 4th, 2009, 06:26 PM
Very nice use of extension methods jm!