写一个自己的Dictionary

本文探讨了实体搜索集合类的设计与实现,通过自定义数据结构EntitySearchItem,利用Dictionary进行键值对存储,实现了高效的数据检索。重点介绍了如何在集合中获取特定类型的数据值,并通过实例展示了数据结构的应用场景。
 public class EntitySearchCollection
    {
        public IList<EntitySearchItem> Items { get; set; } // each item is a simple list of key-value pairs
    }


    public class EntitySearchItem : Dictionary<string, object>
    {
        public T GetValue<T>(string key)
        {
            if (base[key] != null)
            {
                var t = typeof(T);
                t = Nullable.GetUnderlyingType(t) ?? t;
                return (T)Convert.ChangeType(base[key], t);
            }
            return default(T);
        }
    }
在 C# 中,判断一个 `Dictionary<TKey, TValue>` 是否已经包含某个键,可以使用其内置的 `.ContainsKey()` 方法。但你想要的是 **一个通用的方法**,能够适用于任何字典类型(比如 `IDictionary<TKey, TValue>`、`Dictionary<TKey, TValue>` 等),并且可以复用。 下面是一个完整、健壮、通用的实现方式: --- ### ✅ 通用方法:判断字典是否已存在指定的键 ```csharp using System; using System.Collections.Generic; public static class DictionaryHelper { /// <summary> /// 判断指定的字典是否包含给定的键。 /// 如果字典为 null,则返回 false。 /// </summary> /// <typeparam name="TKey">字典键的类型</typeparam> /// <typeparam name="TValue">字典值的类型</typeparam> /// <param name="dictionary">要检查的字典</param> /// <param name="key">要查找的键</param> /// <returns>如果字典不为 null 且包含该键,则返回 true;否则返回 false</returns> public static bool ContainsKeySafe<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key) { if (dictionary == null) return false; return dictionary.ContainsKey(key); } } ``` --- ### 🔍 使用示例 ```csharp var studentScores = new Dictionary<string, int> { { "Alice", 95 }, { "Bob", 80 } }; // 检查是否存在键 bool hasAlice = studentScores.ContainsKeySafe("Alice"); // true bool hasCharlie = studentScores.ContainsKeySafe("Charlie"); // false bool hasNull = ((Dictionary<string, int>)null).ContainsKeySafe("Alice"); // false,不会报错 Console.WriteLine(hasAlice); // True Console.WriteLine(hasCharlie); // False Console.WriteLine(hasNull); // False ``` --- ### 📌 解释说明 | 部分 | 说明 | |------|------| | `IDictionary<TKey, TValue>` | 接口类型,兼容所有实现了它的字典类(如 `Dictionary<,>`、自定义字典等) | | `this IDictionary<...>` | 扩展方法语法,让所有字典都能直接调用 `.ContainsKeySafe(...)` | | `if (dictionary == null)` | 安全防护:防止空引用异常 | | `return dictionary.ContainsKey(key);` | 调用标准方法判断是否存在键 | --- ### 💡 更进一步:支持自定义比较器(可选) 如果你希望使用特定的键比较逻辑(例如忽略大小字符串键),可以传入比较器: ```csharp public static bool ContainsKeyWithComparer<TKey, TValue>( this IDictionary<TKey, TValue> dictionary, TKey key, IEqualityComparer<TKey> comparer = null) { if (dictionary == null) return false; comparer ??= EqualityComparer<TKey>.Default; foreach (var k in dictionary.Keys) { if (comparer.Equals(k, key)) return true; } return false; } ``` #### 示例:忽略大小的字符串键 ```csharp var dict = new Dictionary<string, int>(); dict["ALICE"] = 100; bool found = dict.ContainsKeyWithComparer("alice", StringComparer.OrdinalIgnoreCase); Console.WriteLine(found); // True ``` --- ## ✅ 总结 - ✔️ 推荐使用 `ContainsKeySafe` 扩展方法来安全判断键是否存在 - ✔️ 支持 `null` 字典检查,避免 `NullReferenceException` - ✔️ 泛型 + 扩展方法 = 可重用、简洁、类型安全 - ❌ 不要每次都手动 `dict != null && dict.ContainsKey(key)`,封装一次就够了 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值