Y
Y
Yura Mailler2021-10-02 09:12:45
C++ / C#
Yura Mailler, 2021-10-02 09:12:45

How to access an element by index in a Dictionary?

Hello ! I have a dictionary and imagine that I do not know the name of the elements (for example, the user entered the data himself), then the question arises how can I find the element by index in the Dictionary ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
ayazer, 2021-10-02
@Yura111

The dictionary does not guarantee order preservation, therefore, if it is important, you can use a special class
https://docs.microsoft.com/en-us/dotnet/api/system...

var dict = new OrderedDictionary();
dict.Add("test1", 1);
dict.Add("test2", 2);
dict.Add("test3", 3);

var first = dict["test1"];
var second = dict[1];

Console.WriteLine(first); #1
Console.WriteLine(second); #2

A
Artyom Tokarevsky, 2021-10-02
@artemt

With a foreach loop, you can iterate over key+value pairs, or individual keys or values. Not by index number.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question