首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从ac#Dictionary中删除与谓词匹配的多个项目的最佳方法?

从ac#Dictionary中删除与谓词匹配的多个项目的最佳方法是使用LINQ查询。以下是一个示例代码:

代码语言:csharp
复制
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> acDictionary = new Dictionary<string, string>
        {
            { "apple", "fruit" },
            { "banana", "fruit" },
            { "carrot", "vegetable" },
            { "orange", "fruit" },
            { "potato", "vegetable" }
        };

        Func<KeyValuePair<string, string>, bool> predicate = kvp => kvp.Value == "fruit";

        var matchingItems = acDictionary.Where(predicate);

        foreach (var item in matchingItems)
        {
            acDictionary.Remove(item.Key);
        }

        Console.WriteLine("Updated Dictionary:");
        foreach (var item in acDictionary)
        {
            Console.WriteLine($"{item.Key} - {item.Value}");
        }
    }
}

在这个示例中,我们创建了一个名为acDictionary的字典,其中包含了一些水果和蔬菜。我们定义了一个谓词,该谓词将匹配值为“fruit”的所有项目。然后,我们使用LINQ查询来查找与谓词匹配的所有项目,并将其存储在matchingItems变量中。最后,我们遍历matchingItems并从字典中删除每个匹配项。

这种方法非常简单,并且可以很容易地适应各种不同的情况。使用LINQ查询,您可以轻松地根据任何条件筛选和操作字典中的项目。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券