Skip to content

Instantly share code, notes, and snippets.

@vbjay
Created May 7, 2017 22:29
Show Gist options
  • Save vbjay/66ff2ab0853674c6d51d9dd46bdb41a2 to your computer and use it in GitHub Desktop.
Save vbjay/66ff2ab0853674c6d51d9dd46bdb41a2 to your computer and use it in GitHub Desktop.
Randomize listbox
Imports System.Runtime.CompilerServices
Module Extensions
<Extension>
Iterator Function Randomize(Of T)(items As IEnumerable(Of T)) As IEnumerable(Of T)
Dim indexes As List(Of Integer) = Enumerable.Range(0, items.Count).ToList
Dim rand As New Random
While indexes.Count > 0
Dim tmp As Integer = rand.Next(0, indexes.Count)
Yield items.ElementAt(indexes(tmp))
indexes.RemoveAt(tmp)
End While
End Function
End Module
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim items = Enumerable.Range(0, 20)
ListBox1.Items.AddRange(items.Cast(Of Object)().ToArray)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim items = ListBox1.Items.Cast(Of Object).Select(Function(i) CInt(i)).Randomize.ToArray
ListBox1.Items.Clear()
ListBox1.Items.AddRange(items.Cast(Of Object)().ToArray)
End Sub
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment