首页 > 解决方案 > 如何在没有重复字典名称和键的情况下将其写在一行中?

问题描述

如何在没有重复字典名称和键的情况下在一行中用c#(最新版本)编写此代码:

someDict[key] = someDict[key].MakeSomeChanges(1);

我发现了类似的东西:

_ = someDict[key].MakeSomeChanges(1);

但不幸的是,没有分配改变的价值。

public static int[] MakeSomeChanges(this int[] array, int a)
{
    //some logic
    return x.ToArray();
}

有任何想法吗?

标签: c#operators

解决方案


不确定跟随是否有帮助,它也不是一行,但它可能是一种避免重复的方法,并且可用于任何修改或字典类型。

由于您已经使用了扩展方法,请添加另一个:

public static void Modify<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue intialValue, Func<TValue, TValue> modify)
{
    bool exists = dict.TryGetValue(key, out TValue existingValue);
    TValue value = exists ? existingValue : intialValue;
    dict[key] = modify(value);
}

有了这个,你可以使用:

someDict.Modify(key, new int[0], arr => arr.MakeSomeChanges(1)); 

哪里MakeSomeChanges可能是方法调用(如上)或内联逻辑。


推荐阅读