c# - IDictionary<TKey, TValue> 的 LINQ?有没有我似乎找不到的 AddIf?

标签 c# linq dictionary predicate

基本上,我想知道是否已经存在一种方法:

现在我有:

if (func())
{
    dictionary.add(KeyA, ValueA);
}

if (func2(myString))
{
    dictionary.add(KeyB, ValueB);
}

if (anonymous predicate)
{
    dictionary.Add(KeyC, ValueC);
}

是否已经存在一种方法:

dictionary.AddIf(KeyA, ValueA, ...)
//etc?

我使用 System.Linq 添加了,但它不在那里。

最佳答案

没有内置任何内容 - 我认为这种语法并不直观,但您可以编写自己的扩展方法来帮助您:

public static class DictionaryHelper
{
    public static void AddIf<T, U>(this Dictionary<T, U> dict,
                                   T key, 
                                   U value, 
                                   Predicate<T> pred)
    {
        if (pred(key))
            dict.Add(key, value);
    }
}

示例用法:

Dictionary<string, string> dict = new Dictionary<string, string>();
Predicate<string> predicate =  key => { return key.Length == 3; };

dict.AddIf("foo", "bar", predicate); //foo added
dict.AddIf("tooLong", "baz", predicate); //toolong not added

关于c# - IDictionary<TKey, TValue> 的 LINQ?有没有我似乎找不到的 AddIf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6836649/

相关文章:

c# - 按名称对 FileSystemInfo[] 排序

c# - 如何在 iTextSharp 中旋转文本?

c# - Amazon EC2 上的实时 TCP/IP 套接字服务器

c# - 使用 linq 删除列表中的重复项

c# - 类似 .Net string.CompareOrdinal 的 Linq 函数

java - 重构建议: maps to POJOs

Python - 解析 JSON 数据集

c# - 免费的 C# XML Diff 库或类

c# - 使用属性名称的字符串表示在 LINQ C# 中计算平均值

Python func_dict 用于内存;其他有用的技巧?