Q:

Random value from Dictionary?

var dd = new Dictionary<Guid, object>(); //readonly in my real code
dd.Add( Guid.NewGuid() , 'a');
dd.Add( Guid.NewGuid() , 'a');
dd.Add( Guid.NewGuid() , 'a');
var randone = dd.ElementAt(new Random(dd.Count()).Next(dd.Count));

I want to get a random value from dd as fast as possible (every ms counts), but I am pretty sure I am not doing that with the above sample. How can randone be redone to get a random KeyValuePair? In the actual code, the key is in fact a GUID but the value is a custom POCO.

A:

If you can keep all the keys in a List<T> then you can just choose a random number between 0 and List.Count. Index into the list using that number (simple lookup) and then use that to index into your dictionary.

