请尊重原作者的工作,转载时请务必注明转载自:www.xionggf.com
你想要在C#中实现这样的功能:给定一个目标值,检查Dictionary中是否存在该值,如果存在,就将所有包含这个值的键值对都从字典中移除。
实现思路 要实现这个需求,需要注意一个关键问题:不能在遍历字典的同时直接修改字典(会抛出InvalidOperationException)。因此,正确的步骤是:
先遍历字典,找出所有值等于目标值的键,存入一个临时集合(如List<TKey>)。 遍历这个临时集合,根据其中的键从字典中移除对应的键值对。 完整代码示例 以下是通用的泛型实现,适用于任意类型的Dictionary(只要值类型支持相等比较):
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // 示例字典:键为int,值为string Dictionary<int, string> testDict = new Dictionary<int, string>() { { 1, "苹果" }, { 2, "香蕉" }, { 3, "苹果" }, { 4, "橙子" }, { 5, "苹果" } }; Console.WriteLine("移除前的字典:"); PrintDictionary(testDict); // 要移除的目标值 string targetValue = "苹果"; // 调用方法移除所有值为"苹果"的键值对 RemoveAllEntriesByValue(testDict, targetValue); Console.WriteLine($"\n移除值为\"{targetValue}\"的所有项后:"); PrintDictionary(testDict); } /// <summary> /// 移除Dictionary中所有值等于目标值的键值对 /// </summary> /// <typeparam name="TKey">字典键的类型</typeparam> /// <typeparam name="TValue">字典值的类型</typeparam> /// <param name="dictionary">要操作的字典</param> /// <param name="targetValue">要移除的目标值</param> public static void RemoveAllEntriesByValue<TKey, TValue>(Dictionary<TKey, TValue> dictionary, TValue targetValue) where TKey : notnull // 约束键不能为null(Dictionary的默认要求) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary), "字典不能为null"); } // 第一步:找出所有值等于目标值的键(存入临时列表,避免遍历中修改字典) List<TKey> keysToRemove = dictionary .