Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access value in an Ordered Dictionary when even one of the keys is an integer?

I have an OrderedDictionary as shown in the below code snippet where keys are strings, integer and character .

Well I am quite new to OrderedDictionary and all I know is that an ordered dictionary can store any type of key/value pairs and we can access values through both index and keys.

        OrderedDictionary od = new OrderedDictionary();

        od.Add("Key1", "Val1");
        od.Add("Key2", "Val2");
        od.Add("Key3", "Val3");
        od.Add(1, "Val4");
        od.Add('k', 'V');

So, I was wondering if I need to access Val4 above, then how should I do it? Because when I am trying to use

        Console.WriteLine(od[1]);

it is giving me 'Val2' as it is clearly considering '1' as an index.

Many Thanks!

like image 638
pradeepradyumna Avatar asked Feb 17 '16 05:02

pradeepradyumna


People also ask

What is OrderedDict in Python?

Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.

Is there an ordered dictionary in C#?

OrderedDictionary Class represents a collection of key/value pairs that are accessible by the key or index. It is present in System. Collections.

Is ordered dictionary thread safe?

Explicit Interface Implementations Gets a value indicating whether access to the OrderedDictionary object is synchronized (thread-safe).

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined. If you need an ordered collection of values, I recommend using an array.


1 Answers

You can cast the integer value of 1 to object to hit the correct indexer.

Console.WriteLine(od[(object)1]);
like image 124
Janne Matikainen Avatar answered Sep 22 '22 11:09

Janne Matikainen