C# Dictionary GetKey

Date: 2020-05-14
public static T GetKey<T, K>(Dictionary<K, T> dict, K key)
{
	if (key == null)
		return default;
	return dict.TryGetValue(key, out T value) ? value : default;
}


// example: GetKey(dict, key)?.Name

As extension method:

public static class DictionaryExtensions
{
	public static T GetKey<T, K>(this Dictionary<K, T> d, K k) => k == null ? default : d.TryGetValue(k, out T v) ? v : default;
}
37460cookie-checkC# Dictionary GetKey