-2

so I have this dictionary:

Dictionary<string, double> ddz = new Dictionary<string, double>();
ddz.Add("Paco", 17); // i want this to be printed
ddz.Add("Martin", 16);
//Console.WriteLine(ddz[0]); this line is being marked as an error

I want to print the first Value in the dictionary. I know I can pretty easily do ddz["Paco"], but for the program, I'm trying to code I need to do it with a number.

Alice
  • 3
  • 1
  • 3
    Dictionary entries are not in a specified order and so cannot be indexed by number. See [Dictionary(TKey, TValue)](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-7.0) – Ňɏssa Pøngjǣrdenlarp Oct 21 '22 at 21:16
  • Further reading here: https://stackoverflow.com/questions/6384710/why-is-a-dictionary-not-ordered#:~:text=First%2C%20a%20Dictionary%20has%20no%20guaranteed%20order%2C%20so,you%20don%27t%20need%20order%2C%20don%27t%20ask%20for%20it. – Steve Oct 21 '22 at 21:22

1 Answers1

0

Standard dictionary doesn't preserve order, but you have 2 options for redesigning your code:

Using an OrderedDictionary

OrderedDictionary ddz = new OrderedDictionary();
ddz.Add("Paco", 17);
ddz.Add("Martin", 16);

foreach (DictionaryEntry entry in ddz) {
    Console.WriteLine($"{entry.Key}: {entry.Value}"); // Paco: 17
    break;
}

But be careful, an ordered dictionary is slower than a standard one

Using a list of entries

struct People {
    public string Name;
    public int Age;
}

...

var ddz = new List<People>();

// I assume your variables means Name and Age
ddz.Add(new People {
    Name = "Paco",
    Age = 17
});
ddz.Add(new People {
    Name = "Martin",
    Age = 16
});

var first = ddz[0];
Console.WriteLine($"{first.Name}: {first.Age}"); // Paco: 17
Mishin870
  • 125
  • 6