【问题标题】:Suggested structure to maps some strings to some other strings将某些字符串映射到其他字符串的建议结构
【发布时间】:2014-10-02 06:36:18
【问题描述】:

在我的控制台应用程序中,我有一百个县代码及其名称。例如:

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

当我的程序使用这些值时,它会读取“01”、“02”……而我想要得到“Floyd”等……

这个列表将来不会增长,我只是在硬编码它们,你建议如何访问这些? 也许在静态类中?也许是 JSON 格式?其他方式?

【问题讨论】:

  • 令我困惑的是,您知道字典,正如您的问题 here 所暗示的那样
  • @Noctis 我的身份证说明了一切!

标签: c# string collections keyvaluepair


【解决方案1】:

字典就是你要找的东西:MSDN link

简短示例:

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

}

【讨论】:

  • 也许你可以删除 Dump 调用;即使 Linqpad 非常棒,它也会分散你的注意力
  • @samy Fine ... 就这样... :) ... 稍微梳理一下。
【解决方案2】:

只需使用简单的Dictionary&lt;string, string&gt;;如果你真的想要,你可以将它包装在一个类中以添加一些行为,例如处理未找到或已经存在的键

【讨论】:

    【解决方案3】:

    您正在寻找Dictionary&lt;string, string&gt;

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

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 1970-01-01
      • 2017-12-05
      • 2012-08-21
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 2012-01-23
      • 1970-01-01
      相关资源
      最近更新 更多