Dizionari C # ValueOrNull / ValueorDefault
-
05-07-2019 - |
Domanda
Attualmente sto usando
var x = dict.ContainsKey(key) ? dict[key] : defaultValue
Vorrei in qualche modo che il dizionario [key] restituisse null per chiavi inesistenti, quindi potrei scrivere qualcosa del tipo
var x = dict[key] ?? defaultValue;
questo finisce anche per far parte delle query linq ecc., quindi preferirei soluzioni a una riga.
Soluzione
Con un metodo di estensione:
public static class MyHelper
{
public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic,
K key,
V defaultVal = default(V))
{
V ret;
bool found = dic.TryGetValue(key, out ret);
if (found) { return ret; }
return defaultVal;
}
void Example()
{
var dict = new Dictionary<int, string>();
dict.GetValueOrDefault(42, "default");
}
}
Altri suggerimenti
Puoi usare un metodo helper:
public abstract class MyHelper {
public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {
V ret;
bool found = dic.TryGetValue( key, out ret );
if ( found ) { return ret; }
return default(V);
}
}
var x = MyHelper.GetValueOrDefault( dic, key );
Ecco il " ultimate " soluzione, in quanto implementata come metodo di estensione, utilizza l'interfaccia IDictionary, fornisce un valore predefinito opzionale ed è scritta in modo conciso.
public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dic, TK key,
TV defaultVal=default(TV))
{
TV val;
return dic.TryGetValue(key, out val)
? val
: defaultVal;
}
Non è semplicemente TryGetValue (chiave, valore out)
quello che stai cercando? Citando MSDN:
When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.
da http://msdn.microsoft. com / it-it / library / bb347013 (v = VS.90) aspx
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow