Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to items in Dictionary<string, string> by integer index?

I made a Dictionary<string, string> collection so that I can quickly reference the items by their string identifier.

But I now also need to access this collective by index counter (foreach won't work in my real example).

What do I have to do to the collection below so that I can access its items via integer index as well?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestDict92929
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> events = new Dictionary<string, string>();

            events.Add("first", "this is the first one");
            events.Add("second", "this is the second one");
            events.Add("third", "this is the third one");

            string description = events["second"];
            Console.WriteLine(description);

            string description = events[1]; //error
            Console.WriteLine(description);
        }
    }
}
like image 478
Edward Tanguay Avatar asked Mar 08 '10 15:03

Edward Tanguay


2 Answers

You can't. And your question infers your belief that Dictionary<TKey, TValue> is an ordered list. It is not. If you need an ordered dictionary, this type isn't for you.

Perhaps OrderedDictionary is your friend. It provides integer indexing.

like image 155
Andrew Arnott Avatar answered Sep 19 '22 00:09

Andrew Arnott


You can not. As was said - a dictionary has no order.

Make your OWN CONTAINER that exposes IList and IDictionary... and internally manages both (list and dictionary). This is what I do in those cases. So, I can use both methods.

Basically

class MyOwnContainer : IList, IDictionary

and then internally

IList _list = xxx
IDictionary _dictionary = xxx

then in add / remove / change... update both.

like image 36
TomTom Avatar answered Sep 22 '22 00:09

TomTom