一、【统计总数】有Key则累加,无Key则赋值
Dictionary<string, int> dict = new Dictionary<string, int>();
string key = "key";
int value = 1;
dict[key] = dict.ContainsKey(key) ? dict[key] + value : value;
二、【添加】
有Key则不变,无Key则赋值
dict[key] = dict.ContainsKey(key) ? dict[key] : value;
有Key则用新值覆盖,无Key则赋值
dic[key] = dic.TryGetValue(key, out int existingValue) ? value : dic[key] = value;
元组作为值
Dictionary<string, Tuple<string, string>> dict = new Dictionary<string, Tuple<string, string>>();
// 添加键值对
dict.Add("小明", new Tuple<string, string>("001", "优秀"));
// 单独打印元组的第一个值和第二个值
var tuple = dict["小明"];
Console.WriteLine("第一个值: " + tuple.Item1);
Console.WriteLine("第二个值: " + tuple.Item2);
三、【筛选和查找】
共含4中筛选情况:
Dictionary<int, int> dic = new Dictionary<int, int>();
dic.Add(1, 3);
dic.Add(2, 3);
//1.根据Value找Key(结果可能多个)
List<int> value = dic.Where(x => x.Value == 3).Select(x => x.Key).ToList();
//2.根据Value找Dic(结果可能多个)
List<KeyValuePair<int, int>> result = dic.Where(x => x.Value == 3).ToList();
//3.根据Key找Value
int value2 = dic.Where(x => x.Key == 1).Select(x => x.Value).FirstOrDefault();
//4.根据Key找Dic
KeyValuePair<int, int> result2 = dic.FirstOrDefault(x => x.Key == 1);
四、【提取】键/值列表
var list = dict.Keys.ToList();
var list2 = dict.Values.ToList();
五、【转换】泛型列表转字典
Dictionary<int, int> dictionary = students.ToDictionary(x => x.Id,x => x.Score);//students是一个泛型列表
六、【初始化】初始化传参
// 字典初始化传参
Method(
new Dictionary<string, string>
{
{ "Key1", "Value1" },
{ "Key2", "Value2" },
{ "Key3", "Value3" }
};
);
七、【访问】尝试访问key防报错
//方案一:
var dic = new Dictionary<string, int>() { { "abc", 2 } };//新建字典
var result = 0;//存储结果的值(默认值为0)
dic.TryGetValue("abc", out result);//如果找到key,则返回对应value给rusult,否则返回默认值0
//方案二:
if (dic.ContainsKey("abc"))
{
result = dic["abc"];
}