user1353517
user1353517

Reputation: 300

C# random entry from a dictionary on button click

I have this working code for my dictionary:

dict = new Dictionary<string, string>();

using (StreamReader read = new StreamReader("dictionaryfile.csv"))
{
      string line;
      while ((line = read.ReadLine()) != null)
      {
          string[] splitword = line.Split(',');  
          dict.Add(splitword[0], splitword[1]);
      }
}

I've added a button to my Windows form, and how would I assign a random entry from my dictionary to show in a message box from the button click?

Upvotes: 2

Views: 8358

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460268

You're probably looking for the Random class and an OrderedDictionary:

var dict = new System.Collections.Specialized.OrderedDictionary(); 
dict.Add("key1", "value1");
dict.Add("key2", "value2");
dict.Add("key3", "value3");
dict.Add("key4", "value4");
// get a random value 
var rnd = new Random();
var randomValue = (String)dict[rnd.Next(0, dict.Count)];

Edit: Here's an approach using a Dictionary<String,String> and the ElementAt method:

var rnd = new Random();
var randomEntry = dict.ElementAt(rnd.Next(0, dict.Count));
String randomKey = randomEntry.Key;
String randomValue = randomEntry.Value;

Note that you should not create the random instance in a method, you should either pass it as parameter or use a member variable: https://stackoverflow.com/a/768001/284240

Upvotes: 5

Related Questions