Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get A random keyValue from Hashtable

Tags:

performance

c#

I Have a Hashtable that I dont know What is the content of .

now I want to get one Key and value from it;

I use hashtable because of its speed because content of hashtable is over 4,500,000 KeyValuePair so I cant use GetEnumerator its reduce program speed

like image 809
Hamid Avatar asked Dec 06 '22 12:12

Hamid


1 Answers

You use a List<TKey>:

Dictionary<string, string> dict = ... your hashtable which could be huge

List<string> keys = new List<string>(dict.Keys);
int size = dict.Count;
Random rand = new Random();
string randomKey = keys[rand.Next(size)];

We are just creating a List<TKey> whose elements are pointing to the same location in memory as the keys of your hashtable and then we pick a random element from this list.

And if you want to get a random element value from the hashtable, this should be pretty straightforward given a random key.

string randomeElement = dict[randomKey];
like image 77
Darin Dimitrov Avatar answered Dec 24 '22 07:12

Darin Dimitrov