Languages
[Edit]
PL

C # / .NET - pobierz losowy element klucz-wartość ze słownika

0 points
Created by:
Mohammad-Oneal
327

W klasie Dictionary C # / .NET istnieje odpowiednik Java HashMap - zobacz ten post.

Szybkie rozwiązanie:

Uwaga:

Poniższy przykład używa Linq , więc załączamy go z: 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);

Spójrz na poniższy przykład.

1. Przykład metod Linq oraz ElementAt

W tej sekcji można znaleźć pełny przykład wykorzystania metody Linq.

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);
		}
	}
}

Wynik:

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

Uwaga:

w powyższym przykładzie użyto metody Linq Enuberable.ElementAt do pobrania elementu.

Referencje:

  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 (PL)

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