Is there an easy way to randomize a list in VB.NET?
list, random, vb.net, visual-studio-2008
Solution
Build a Comparer:
Public Class Randomizer(Of T)
Implements IComparer(Of T)
''// Ensures different instances are sorted in different orders
Private Shared Salter As New Random() ''// only as random as your seed
Private Salt As Integer
Public Sub New()
Salt = Salter.Next(Integer.MinValue, Integer.MaxValue)
End Sub
Private Shared sha As New SHA1CryptoServiceProvider()
Private Function HashNSalt(ByVal x As Integer) As Integer
Dim b() As Byte = sha.ComputeHash(BitConverter.GetBytes(x))
Dim r As Integer = 0
For i As Integer = 0 To b.Length - 1 Step 4
r = r Xor BitConverter.ToInt32(b, i)
Next
Return r Xor Salt
End Function
Public Function Compare(x As T, y As T) As Integer _
Implements IComparer(Of T).Compare
Return HashNSalt(x.GetHashCode()).CompareTo(HashNSalt(y.GetHashCode()))
End Function
End Class
Use it like this, assuming you mean a generic `List(Of FileInfo)`:
list.Sort(New Randomizer(Of IO.FileInfo)())
You can also use a closure to make the random value 'sticky' and then just use linq's .OrderBy() on that (C# this time, because the VB lambda syntax is ugly):
list = list.OrderBy(a => Guid.NewGuid()).ToList();
Explained here, along with why it might not even be as fast as real shuffle: http://www.codinghorror.com/blog/archives/001008.html?r=31644
Problem
I have a list of type `System.IO.FileInfo`, and I would like to randomize the list. I thought I remember seeing something like `list.randomize()` a little while back but I cannot find where I may have seen that. My first foray into this yielded me with this function: ``` Private Shared Sub GetRandom(ByVal oMax As Integer, ByRef currentVals As List(Of Integer)) Dim oRand As New Random(Now.Millisecond) Dim oTemp As Integer = -1 Do Until currentVals.Count = IMG_COUNT oTemp = oRand.Next(1, oMax) If Not currentVals.Contains(oTemp) Then currentVals.Add(oTemp) Loop End Sub ``` I send it the max val I want it to iterate up to, and a reference to the list I want the randomized content in. The variable `IMG_COUNT` is set farther up in the script, designating how many random images I want displayed. Thanks guys, I appreciate it :D