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.
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.