Top community members

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

[Edit]
EN

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

12 points
Created by:
JustMike
3364

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

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more