src/DotNetCommon.Core/Extensions/DictionaryExtensions.cs

(开头部分) 13KB

这里只显示每个文件的开头 60 行。登录后可以解锁完整代码。

namespace DotNetCommon.Extensions
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;
    using System.Reflection;

    /// <summary>
    /// <see cref="System.Collections.Generic.IDictionary{TKey, TValue}"/> 扩展类
    /// </summary>
    public static class DictionaryExtensions
    {
        /// <summary>
        /// 从<paramref name="dictionary"/>中获取值,如果指定的 <paramref name="key"/> 不存在的话,就将<paramref name="value"/>添加进去
        /// </summary>
        public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
        {
            if (dictionary.TryGetValue(key, out var result)) { return result; }

            dictionary[key] = value;
            return value;
        }

        /// <summary>
        /// 从<paramref name="dictionary"/>中获取值,如果指定的 <paramref name="key"/> 不存在的话,就调用<paramref name="valueCreator"/>生成值并添加进去
        /// </summary>
        public static TValue GetOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, Func<TValue> valueCreator)
        {
            if (dictionary.TryGetValue(key, out var result)) { return result; }

            var value = valueCreator();
            dictionary[key] = value;
            result = value;
            return result;
        }

        /// <summary>
        /// 从<paramref name="dictionary"/>中获取值,如果指定的 <paramref name="key"/> 不存在的话,返回指定的 <paramref name="defaultValue"/>
        /// </summary>
        public static TValue GetOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary,
            TKey key, TValue defaultValue = default)
                => dictionary.TryGetValue(key, out var value) ? value : defaultValue;

        /// <summary>
        /// 将给定的字典 <paramref name="pairsToAdd"/> 中的数据添加到当前字典中
        /// </summary>
        public static void Add<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, IDictionary<TKey, TValue> pairsToAdd)
        {
            foreach (var pair in pairsToAdd)
            {
                dictionary.Add(pair.Key, pair.Value);
            }
        }

        /// <summary>
        /// 比较当前字典和给定的字典 <paramref name="right"/> 是否相等,使用<paramref name="valueComparer"/>比较器对集合中的元素进行比较
后面还有 288 行代码,解锁后查看完整代码

24 小时内免费解锁 3 个项目,之后 1 积分/个。 规则说明

AI 解读

登录后可用,每次 10 积分,解读结果公开显示在下面。

还没有人解读过这个文件。