gpt4 book ai didi

c# - .NET 字典 : get or create new

转载 作者:IT王子 更新时间:2023-10-29 04:03:43 26 4
gpt4 key购买 nike

我经常发现自己创建了一个 Dictionary具有非平凡的值类(例如 List ),然后在填充数据时始终编写相同的代码模式。

例如:

var dict = new Dictionary<string, List<string>>();
string key = "foo";
string aValueForKey = "bar";

也就是我想插入"bar"到键"foo"对应的列表中,其中键"foo"可能没有映射到任何东西。

这是我使用不断重复的模式的地方:

List<string> keyValues;
if (!dict.TryGetValue(key, out keyValues))
dict.Add(key, keyValues = new List<string>());
keyValues.Add(aValueForKey);

有没有更优雅的方式来做到这一点?

本题没有答案的相关问题:

最佳答案

我们对此的看法略有不同,但效果是相似的:

public static TValue GetOrCreate<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key) 
where TValue : new()
{
if (!dict.TryGetValue(key, out TValue val))
{
val = new TValue();
dict.Add(key, val);
}

return val;
}

调用:

var dictionary = new Dictionary<string, List<int>>();

List<int> numbers = dictionary.GetOrCreate("key");

它对公共(public)无参数构造函数使用通用约束:where TValue : new()

为了帮助发现,除非扩展方法非常特定于一个狭窄的问题,否则我们倾向于将扩展方法放在它们正在扩展的类型的命名空间中,在这种情况下:

namespace System.Collections.Generic

大多数时候,使用该类型的人在顶部定义了 using 语句,因此 IntelliSense 也会在您的代码中找到为它定义的扩展方法。

关于c# - .NET 字典 : get or create new,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16192906/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com