我如何在没有重复的字典名称和键的情况下将其写在一行中?
How can I write this in one line without duplicate dictionary name and key?
如何在没有重复字典名称和键的情况下用 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
可以是方法调用(如上)或内联逻辑。
如何在没有重复字典名称和键的情况下用 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
可以是方法调用(如上)或内联逻辑。