Dictionary
AddOrUpdate(添加或更新)
Dictionary<int, string> dict = new();
dict
.AddOrUpdate(new KeyValuePair<int, string>(1, "1"))
.AddOrUpdate(new KeyValuePair<int, string>(1, "1"))
.AddOrUpdate(1, "2");
// 1 : "2"
tip
支持传入 KeyValuePair
和 单独的 key+value
AddRange(添加多个)
Dictionary<int, string> dict = new();
Dictionary<int, string> dict2 = new()
{
{ 1, "1" },
{ 2, "2" },
{ 3, "3" },
};
dict.AddRange(dict2);
// 1 : "1"
// 2 : "2"
// 3 : "3"
tip
支持传入 KeyValuePair
集合
ToDictionary(将集合转为字典)
string[] nums = new[] { "1", "2", "3", "4", "5" };
IDictionary<int, string> dict = nums.ToDictionary(item => int.Parse(item));
tip
需要使用委托指定字典的 Key
值
GetAndRemove/Pop(获取并移除)
Dictionary<int, string> dict = new()
{
{ 1, "1" },
{ 2, "2" },
{ 3, "3" },
};
string value = dict.GetAndRemove(1);
tip
实际上使用 Pop 也可以
dict.Pop(1)
Deconstruct(解构)
Dictionary<int, string> dict = new()
{
{ 1, "1" },
{ 2, "2" },
{ 3, "3" },
};
foreach (var (value, index) in dict.Deconstruct())
;