I try to write my own extensions as needed.
For example, GetValueOrDefault as follows:
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> @this, K key, Func<V> @default) { return @this.ContainsKey(key) ? @this[key] : @default(); }
It can be used as follows:
var password = accounts.GetValueOrDefault(username, () => null); if (password != null) { //do stuff }
Or SetValueIfExists :
public static V SetValueIfExists<K, V>(this IDictionary<K, V> @this, K key, V value) { if (@this.ContainsKey(key)) { @this[key] = value; } }
Or SetValueIfNotExists :
public static V SetValueIfNotExists<K, V>(this IDictionary<K, V> @this, K key, V value) { if ( !@this.ContainsKey (key)) { @this[key] = value; } }
Enigmativity
source share