Question Randomize ConcurrentDictionary

cknipe

New member
Joined
Jan 29, 2015
Messages
1
Programming Experience
3-5
Hi All,

Sorry for perhaps a rather silly question, but I just can't seem to find this...

I have an ConcurrentDictionary (threaded application), and the threads loop through the items in the dictionary using an For Each loop...

How can I randomize the keys in the ConcurrentDictionary each time after my For Each loop has completed?
 
You can randomize the keys using Random class and iterate them:
Private rnd As New Random

        Dim randomkeys = list.Keys.OrderBy(Function() rnd.Next)
        For Each key In randomkeys
            'use list(key)
        Next

Notice that if you keep and use this 'randomkeys' result for later, then it will randomize each time you iterate it. Reason is it is a reference to a Linq expression, a IOrderedEnumerable(Of T), and that expression is evaluated each time it is accessed. You can read about Query Execution here: Writing Your First LINQ Query (Visual Basic)
 
Back
Top