C#基础:字典的用法

一、【统计总数】有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"];
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值