A For Each statement that visits items in random order

At times you may need to process elements of an array, a collection, or a dictionary object in random order, for example when sampling a population or (more often) when writing a game, such as a card game. Here’s a class that you can use in a For Each statement to randomly process all the elements of any data structure that implements the IEnumerable interface:

Class RandomIterator    Implements IEnumerable    ' a low-overhead ArrayList to store references    Dim items As New ArrayList()    Sub New(ByVal collection As IEnumerable, ByVal seed As Integer)        ' load all the items in the ArrayList, but in random order        Dim rand As New Random(seed)        Dim o As Object        For Each o In collection            Items.Insert(Rand.Next(0, Items.Count + 1), o)        Next    End Sub    Public Function GetEnumerator() As System.Collections.IEnumerator _        Implements System.Collections.IEnumerable.GetEnumerator        ' return the enumerator of the inner ArrayList        Return items.GetEnumerator()    End FunctionEnd Class

This code shows how you can use the RandomIterator class to randomly process all the elements in a string array, but you can use it with collection and dictionaries alike:

Dim arr() As String = {"one", "two", "three", "four", "five" }Dim s As String' the sequence you obtain depends on the seed you pass as the 2nd argumentFor Each s In New RandomIterator(arr, 1234)    Console.WriteLine(s)Next

This code produces the following sequence:


Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS