C#开发中如何为Dictionary字典的已有键追加对应值
你只需要补充键存在时的处理逻辑即可:当键已经存在于字典中时,直接取出该键对应的HashSet<string>对象,调用其Add方法追加值就行,HashSet本身会自动去重,不会存入重复的x.name。
基础修改版(在你原有代码基础上补充)
Dictionary<string,HashSet<string>> container = new Dictionary<string,HashSet<string>>(); foreach(dynamic x in records) { if(!container.ContainsKey(x.code)) { HashSet<string> item = new HashSet<string>(); item.Add(x.name); container.Add(x.code,item); } else { // 键已存在,直接取出对应HashSet追加值 container[x.code].Add(x.name); } }
性能优化版
上面的写法在判断键存在、以及后续取值时会触发两次字典查找,用TryGetValue可以把查找次数减少到1次,效率更高:
Dictionary<string,HashSet<string>> container = new Dictionary<string,HashSet<string>>(); foreach(dynamic x in records) { // 一次查找同时完成存在判断和取值 if(container.TryGetValue(x.code, out var targetSet)) { targetSet.Add(x.name); } else { container.Add(x.code, new HashSet<string>{x.name}); } }
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

