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
.
Random random = new Random();
Dictionary<string, int> dictionary = ...
int index = random.Next(dictionary.Count);
string key = dictionary.Keys.ElementAt(index);
int value = dictionary.Values.ElementAt(index);
KeyValuePair<string, int> pair = dictionary.ElementAt(index);
Take a look at the example below:
1. Linq
and ElementAt
method
example
Linq
and ElementAt
methodIn this section you can find full example that uses Linq method.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public static void Main(string[] args)
{
Random random = new Random();
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("a", 11);
dictionary.Add("b", 22);
dictionary.Add("c", 33);
dictionary.Add("d", 44);
dictionary.Add("e", 55);
for (int i = 0; i < 10; ++i)
{
int index = random.Next(dictionary.Count);
//string key = dictionary.Keys.ElementAt(index);
//int value = dictionary.Values.ElementAt(index);
KeyValuePair<string, int> pair = dictionary.ElementAt(index);
Console.WriteLine("key: " + pair.Key + ", value: " + pair.Value);
}
}
}
Output:
key: e, value: 55
key: e, value: 55
key: d, value: 44
key: b, value: 22
key: c, value: 33
key: a, value: 11
key: b, value: 22
key: b, value: 22
key: a, value: 11
key: d, value: 44
Note: in above example Enuberable.ElementAt
Linq method has been used to get element.