How to randomly shuffle the items inside a dictionary .

i have come across a this kind of situation in one of my projects where i need to randomly shuffle the dicitionary . we are going to take a quick look at an easy and simple way to randomize a dictionary, which is most likely something that you may be using in a complex application.


so let's get started . Before that we need to create a simple dictionary and assign some elements into that

code :

Dictionary<String, int> myDictionary= new Dictionary<string, int>();

for (int i = 0; i < 50; i++)
  myDictionary.Add("number" + i.ToString(), i);

Elements inside dictionary :

// "number 0" -> 0
// "number 1" -> 1
// "number 2" -> 2
and so on .

so now we have created a simple dictionary and inserted some integers into it .


Now let's look at how we can shuffle this dicitonary and provide a random output of number.[being our main task ].

Yeah, you guessed it right , it requires rather complex algorithm to accomplish this task , but we have LINQ which comes to rescue at this point of time . let's look into it and see how we can achieve this using LINQ.  

Most collections in .Net implement the IEnumerable interface,this interface allows us to use the OrderBy extension method provided by the System.Linq namespace. As you may have guessed, this takes a collection and orders it. To make things even easier, this function allows some pretty fancy Lamda functions, so we can actually order our Dictionary with just one line of code.

However, we want to shuffle our Dictionary. To do this, we have to order it by a random value. To do this we basically pass in a function that chooses a random number for the index. When we combine the ordering and random index together, our code looks something like so:

code :
Random rand = new Random();
myDictionary= myDictionary.OrderBy(x => rand.Next())
.ToDictionary(item => item.Key, item => item.Value);


now when you print the dictionary you will get randomly shuffled items .

output :

// "number 10" -> 10
// "number 17" -> 17
// "number 25" -> 25
and so on .


I hope this might be helpful to some one some day ...............