EN
C# / .NET - get random key value element from dictionary
12 points
In C# / .NET Dictionary
class is Java HashMap
class equivalent - see this post.
Quick solution:
Note: below example uses Linq, so include it with:
using System.Linq
.
xxxxxxxxxx
1
Random random = new Random();
2
Dictionary<string, int> dictionary = ...
3
4
int index = random.Next(dictionary.Count);
5
6
string key = dictionary.Keys.ElementAt(index);
7
int value = dictionary.Values.ElementAt(index);
8
9
KeyValuePair<string, int> pair = dictionary.ElementAt(index);
Take a look at the example below:
In this section you can find full example that uses Linq method.
xxxxxxxxxx
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
5
class Program
6
{
7
public static void Main(string[] args)
8
{
9
Random random = new Random();
10
Dictionary<string, int> dictionary = new Dictionary<string, int>();
11
12
dictionary.Add("a", 11);
13
dictionary.Add("b", 22);
14
dictionary.Add("c", 33);
15
dictionary.Add("d", 44);
16
dictionary.Add("e", 55);
17
18
for (int i = 0; i < 10; ++i)
19
{
20
int index = random.Next(dictionary.Count);
21
22
//string key = dictionary.Keys.ElementAt(index);
23
//int value = dictionary.Values.ElementAt(index);
24
KeyValuePair<string, int> pair = dictionary.ElementAt(index);
25
26
Console.WriteLine("key: " + pair.Key + ", value: " + pair.Value);
27
}
28
}
29
}
Output:
xxxxxxxxxx
1
key: e, value: 55
2
key: e, value: 55
3
key: d, value: 44
4
key: b, value: 22
5
key: c, value: 33
6
key: a, value: 11
7
key: b, value: 22
8
key: b, value: 22
9
key: a, value: 11
10
key: d, value: 44
Note: in above example Enuberable.ElementAt
Linq method has been used to get element.