C#辞書ValueOrNull / ValueorDefault
-
05-07-2019 - |
質問
現在使用している
var x = dict.ContainsKey(key) ? dict[key] : defaultValue
辞書[キー]が存在しないキーに対してnullを返すようにする方法が欲しいので、次のように書くことができます
var x = dict[key] ?? defaultValue;
これもlinqクエリなどの一部になるため、1行のソリューションをお勧めします。
解決
拡張メソッドを使用:
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");
}
}
他のヒント
ヘルパーメソッドを使用できます:
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 );
これは「究極の」です解決策は、拡張メソッドとして実装され、IDictionaryインターフェイスを使用し、オプションのデフォルト値を提供し、簡潔に記述されている点です。
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;
}
単に TryGetValue(key、out value)
が探しているものではありませんか? 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.
http://msdn.microsoftから。 com / en-us / library / bb347013(v = vs.90).aspx
所属していません StackOverflow