VB version here.
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:
Code:
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:
Code:
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.
EDIT: It's been brought to my attention that there is a significant issue with this code that, while unlikely to be encountered, could cause the operation to fail. Here's a reimplementation that isn't susceptible to this issue:
csharp Code:
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 = items.ToArray();
var keys = Array.ConvertAll(result, item => rng.NextDouble());
Array.Sort(keys, result);
}
return result;
}
}