C# Dictionary用法总结
public static class DictionaryExtensionMethodClass
{
/// <summary>
/// 尝试将键和值添加到字典中:如果不存在,才添加;存在,不添加也不抛导常
/// </summary>
public static Dictionary<TKey, TValue> TryAdd<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
{
if (dict.ContainsKey(key) == false)
dict.Add(key, value);
return dict;
}
/// <summary>
/// 将键和值添加或替换到字典中:如果不存在,,则添加;存在,则替换
/// </summary>
public static Dictionary<TKey, TValue> AddOrPeplace<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue value)
{
dict[key] = value;
return dict;
}
/// <summary>
/// 获取与指定的键相关联的值,如果没有则返回输入的默认值
/// </summary>
public static TValue GetValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
{
return dict.ContainsKey(key)?dict[key] : defaultValue;
}
/// <summary>
/// 向字典中批量添加键值对
/// </summary>
/// <param>如果已存在,是否替换</param>
public static Dictionary<TKey, TValue> AddRange<TKey, TValue>(this Dictionary<TKey, TValue> dict, IEnumerable<KeyValuePair<TKey, TValue>> values, bool replaceExisted)
{
foreach (var item in values)
{
if (dict.ContainsKey(item.Key) == false || replaceExisted)
dict[item.Key] = item.Value;
}
return dict;
}
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67166.html
- 上一篇:C# 使用TimeSpan计算两个时间差
- 下一篇:C#中哈希表与List的比较