It just so happens that I have a project open right now that contains extension methods for randomising a list of objects:
Imports System.Runtime.CompilerServices
''' <summary>
''' Contains methods that extend the <see cref="IEnumerable(Of T)"/> interface.
''' </summary>
Public Module EnumerableExtensions
''' <summary>
''' A random number generator.
''' </summary>
Private rng As Random
''' <summary>
''' Randomises the items in an enumerable list.
''' </summary>
''' <typeparam name="T">
''' The type of the items in the list.
''' </typeparam>
''' <param name="source">
''' The input list.
''' </param>
''' <returns>
''' The items from the input list in random order.
''' </returns>
<Extension>
Public Function Randomize(Of T)(source As IEnumerable(Of T)) As IEnumerable(Of T)
EnsureRandomInitialized()
Return source.Randomize(rng)
End Function
''' <summary>
''' Randomises the items in an enumerable list.
''' </summary>
''' <typeparam name="T">
''' The type of the items in the list.
''' </typeparam>
''' <param name="source">
''' The input list.
''' </param>
''' <param name="random">
''' A random number generator.
''' </param>
''' <returns>
''' The items from the input list in random order.
''' </returns>
<Extension>
Public Function Randomize(Of T)(source As IEnumerable(Of T), random As Random) As IEnumerable(Of T)
Return source.OrderBy(Function(o) random.NextDouble())
End Function
''' <summary>
''' Initialises the random number generator if it is not already.
''' </summary>
Private Sub EnsureRandomInitialized()
rng = If(rng, New Random)
End Sub
End Module
With that module in your project, you can do things like this:
Dim numbers = Enumerable.Range(1, 10).Randomize()
For Each number In numbers
Console.WriteLine(number)
Next
That module contains two overloads, with the second allowing you to pass in your own Random
instance if desired. If you only ever want to use the first overload then the module can be simplified somewhat:
Imports System.Runtime.CompilerServices
''' <summary>
''' Contains methods that extend the <see cref="IEnumerable(Of T)"/> interface.
''' </summary>
Public Module EnumerableExtensions
''' <summary>
''' A random number generator.
''' </summary>
Private rng As Random
''' <summary>
''' Randomises the items in an enumerable list.
''' </summary>
''' <typeparam name="T">
''' The type of the items in the list.
''' </typeparam>
''' <param name="source">
''' The input list.
''' </param>
''' <returns>
''' The items from the input list in random order.
''' </returns>
<Extension>
Public Function Randomize(Of T)(source As IEnumerable(Of T)) As IEnumerable(Of T)
rng = If(rng, New Random)
Return source.OrderBy(Function(o) rng.NextDouble())
End Function
End Module