Yes - use Dictionary.TryGetValue. To get the value, it takes a parameter outand returns the value of the found value. Here is your corrected code:
foreach(var item in newInfo)
{
int value;
if (myDict.TryGetValue(item.Name, out value))
{
myDict[item.Name] = value + item.NewInfo;
}
else
{
myDict[item.Name] = item.NewInfo;
}
}
, . , out 0. item.NewInfo, item.NewInfo + value, . :
foreach(var item in newInfo)
{
int value;
myDict.TryGetValue(item.Name, out value);
myDict[item.Name] = value + item.NewInfo;
}
- , .
, GetValueOrDefault, . , :
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key)
{
TValue value;
dictionary.TryGetValue(key, out value);
return value;
}
public static TValue GetValueOrDefault<TKey, TValue>
(this IDictionary<TKey, TValue> dictionary, TKey key,
TValue customDefault)
{
TValue value;
if (dictionary.TryGetValue(key, out value))
{
return value;
}
else
{
return customDefault;
}
}
:
foreach(var item in newInfo)
{
myDict[item.Name] = myDict.GetValueOrDefault(item.Name) + item.NewInfo;
}
( GetValueOrDefault(item.Name, 0) .)
...
, - /. , TValue - , . , .
- ContainsKey, ( ) . , +=:
myDict[item.Name] = myDict[item.Name] + item.NewInfo;
(item.Name , , .)
Dictionary, " " , ,
bool Update(TKey key, Func<TValue, bool, TValue> replacementFunction)
replacementFunction , ( TValue, ) , , , . , . ( .)