-2

I'm facing a problem with my code. The values has been randomly duplicated, and I'm not sure how to prevent from random duplication.

Here's my code:

public static Dictionary<TKey, TValue> Shuffle<TKey, TValue>(
   this Dictionary<TKey, TValue> source)
{
    Random r = new Random();
    return source.OrderBy(x => r.Next())
       .ToDictionary(item => item.Key, item => item.Value);
}
Corey Adler
  • 15,897
  • 18
  • 66
  • 80
user3044300
  • 45
  • 1
  • 5

1 Answers1

0

In order to avoid duplicate you would need to retain the instance of Random.

Consider the following...

public static Dictionary<TKey, TValue> Shuffle<TKey, TValue>(
   this Dictionary<TKey, TValue> source, Random r)
{
    return source.OrderBy(x => r.Next())
       .ToDictionary(item => item.Key, item => item.Value);
}

Good Luck!

gpmurthy
  • 2,397
  • 19
  • 21
  • thanks but isn't working i couldn't use the shuffle method in dictonary, example : shuffled01 = dict01.Shuffle(); :error no overload for method shuffle 0 arguments – user3044300 Nov 28 '13 at 04:31
  • To call the method you need to pass a reference to a `Random` object. It's been done this way because the `Random` object isn't always very random and you risk duplicate sequences of random numbers if you instantiate two instances in a short period and this could affect your code. I would prefer holding a reference in a static field for this kind of thing. To avoid holding the reference too long I'd wrap it in a `WeakReference` object. – Enigmativity Nov 28 '13 at 05:32