Reputation: 16764
I have the following Dictionary content :
[0] {75, SimpleObject}
[1] {56, SimpleObject}
[2] {65, SimpleObject}
[3] {12, SimpleObject}
...
I want to get first key, means 75, without foreach.
Maybe the key
word should reffers to [0] not 75.
Because based on that key, I want to use that SimpleObject
, I wrote:
SimpleObject s = dictionary[0] as SimpleObject;
but the VS2010 throws an exception:
The given key was not present in the dictionary.
I know that [0]
means key number 0 from dictionary, means if I could have
[0] {72, SimpleObject} //here
[1] {56, SimpleObject}
[2] {65, SimpleObject}
[3] {12, SimpleObject}
...
then I should get the correspondent SimpleObject
.
Sorry, is first time using Dictionary and I want to learn more.
Question: How to get the number 75
and his SimpleObject ?
Thank you.
PS: I know that in StackOverflow already exists similar topic but no of them help me to get that key.
Upvotes: 3
Views: 13130
Reputation: 754763
Not that Dictionary<TKey, TValue>
is an unordered collection hence it has no concept of first or last. The order of the items presented is essentially random. You can't depend on it being the same between instances of your application.
If you do want some order then you should use SortedDictionary<TKey, TValue>
instead. The items presented there are done so in an ordered way and will give you consistent results between runs of your application
// Consistent output is produced below
var dictionary = new SortedDictionary<int, SimpleObject>();
var pair = dictionary.First();
Console.WriteLine("{0} -> {1}", pair.Key, pair.Value);
Upvotes: 5
Reputation: 700362
A dictionary is not an ordered collection, it doesn't have any indexes.
Use the key to access the item:
SimpleObject s = dictionary[75];
Upvotes: 0
Reputation: 160902
75 is the key value not the index:
SimpleObject s = dictionary[75] as SimpleObject;
A Dictionary<T,U>
is unordered so you should not rely on the order of the key value pairs it contains.
Upvotes: 0
Reputation: 33139
A Dictionary
is a (key, value) pair structure without explicit ordering. Maybe what you are looking for would be useful with a SortedDictionary
, but it has no meaning with a regular Dictionary
.
Upvotes: 1
Reputation: 7441
using System.Linq;
...
dictionary.First().Key // Returns 75
dictionary.First().Value // returns the related SimpleObject
Upvotes: 11