-1

In my console application I have one hundred county codes and their names. For example:

"01" : "Floyd"
"02" : "Wabash"

When my program uses the values, it reads "01","02"...and I want to get "Floyd", etc...

This list won't grow in future, I am just hard coding them, How do you suggest to access these? Maybe in a static class? Maybe in a JSON format? Other ways?

JoelC
  • 3,664
  • 9
  • 33
  • 38

3 Answers3

2

Dictionary is what you look for: MSDN link

Short example:

void Main()
{
    var dic = new Dictionary<int,string>();

    // Instead of having a method to check, we use this Action
    Action<int> tryDic = (i) => {
        if (dic.ContainsKey(i))
            Console.WriteLine("{0}:{1}", i, dic[i]);
        else
            Console.WriteLine("dic has no key {0}", i);
    };

    dic.Add(1,"one");
    dic.Add(2,"two");

    // dic.Keys   = 1, 2
    // dic.Values = one, two

    tryDic(1); // one
    tryDic(3); // dic has no key 3 (Happens in Action above)

    dic[1]="wow";
    tryDic(1); // wow

}
Noctis
  • 11,507
  • 3
  • 43
  • 82
1

Just use a simple Dictionary<string, string>; if you really want you can wrap it in a class to add some behavior such as handling keys not found, or already existing

samy
  • 14,832
  • 2
  • 54
  • 82
0

You are looking for a Dictionary<string, string>

var values = new Dictionary<string,string>();
values.Add("01", "Floyd");
...

var value = values["01"]; // Floyd
Selman Genç
  • 100,147
  • 13
  • 119
  • 184