Dictionary
AddOrUpdate(添加或更新)
备注
字典的添加或更新, 当字典中存在相同的key时更新value
支持传入 KeyValuePair
和 单独的 key 和 value
Dictionary<int, string> dict = new();
dict
.AddOrUpdate(new KeyValuePair<int, string>(1, "1"))
.AddOrUpdate(new KeyValuePair<int, string>(1, "1"));
// dict[1]=="2"
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"
ToDictionary
备注
将集合转为字典
string[] nums = new[] { "1", "2", "3", "4", "5" };
IDictionary<int, string> dict = nums.ToDictionary(item => int.Parse(item));
GetAndRemove/Pop
备注
获取字典中的元素并移除
Dictionary<int, string> dict = new()
{
{ 1, "1" },
{ 2, "2" },
{ 3, "3" },
};
string value = dict.GetAndRemove(1);
value = dict.Pop(1);
ToObj<T>
备注
可以将字典转换为指定的对象
Dictionary<string, string> dict2 = new Dictionary<string, string>{
{"username","name"},
{"age","3"},
};
var userinfo = dict1.ToObj<UserInfo>();