CS中使用键值对存取值并使用Linq通过key获取value

场景

有时候需要往数据库中存取数据比如

1,2,3

但是取出来后可能需要对应的中文。

首先新建全局变量类Global,然后声明全局字段来存取键值对。

            Dictionary<string, string> _componentsKeyValue = new Dictionary<string, string>()
            {
                {"1", "霸道"},
                {"2", "流氓"},
                {"3", "气质"},
                {"4", "你好"},
                {"5", "下午好"},
                {"6", "嗯呢"}
            };

然后再新建全局属性来获取此键值对

            public Dictionary<string, string> ComponentsKeyValue
            {
                get
                {
                    return this._componentsKeyValue;
                }
            }

注:

博客主页:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。

实现

然后在需要通过键获取值的地方

string name = Global.ComponentsKeyValue.Where(q => q.Key == "1").First().Value.ToString();

这里的键值对都是使用的string ,具体可以根据自己需要定义字典的键值对的类型。

原文地址:https://www.cnblogs.com/badaoliumangqizhi/p/12752921.html