c# - 如何在没有重复字典名称和键的情况下将其写在一行中?
问题描述
如何在没有重复字典名称和键的情况下在一行中用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();
}
有任何想法吗?
解决方案
不确定跟随是否有帮助,它也不是一行,但它可能是一种避免重复的方法,并且可用于任何修改或字典类型。
由于您已经使用了扩展方法,请添加另一个:
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
可能是方法调用(如上)或内联逻辑。
推荐阅读
- git - Git - 将另一个项目分支克隆到当前项目
- java - 为什么在 MainJFrame/ 中无法识别 arraylist 对象方法
- php - 如何使用 Adldap2-laravel 包更改 AD 用户密码?
- xml - 简单的 Xpath xml
- javascript - 具有动态时间间隔并取决于 disabledTimeIntervals-settings 的表单
- python - 从它包含的多个实例中表示一个包的方法是什么?
- fabricjs - fabric.js - 向形状添加自定义属性
- sql - 我希望 CTE 中的帮助显示表值中的标题名称
- encryption - 如何在可能来自不同设备且服务器不存储任何加密密钥的客户端上加密和解密?
- python - Perform row multiplication in data frame