Languages
[Edit]
EN

C# / .NET - get random key value element from dictionary

12 points
Created by:
Dharman
518

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

In 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.

References:

  1. Random.Next Method - Microsoft Docs
  2. Dictionary<TKey,TValue> Class - Microsoft Docs
  3. Enumerable.ElementAt Method - Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

C# / .NET - random

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join