Jon's answer will work with Dictionary<string, int>
, as that can't have a null key value in the dictionary. It wouldn't work with Dictionary<int, string>
, however, as that doesn't represent a null key value... the "failure" mode would end up with a key of 0.
Two options:
Write a TryFirstOrDefault
method, like this:
public static bool TryFirstOrDefault<T>(this IEnumerable<T> source, out T value)
{
value = default(T);
using (var iterator = source.GetEnumerator())
{
if (iterator.MoveNext())
{
value = iterator.Current;
return true;
}
return false;
}
}
Alternatively, project to a nullable type:
var entry = dict.Where(e => e.Value == 1)
.Select(e => (KeyValuePair<string,int>?) e)
.FirstOrDefault();
if (entry != null)
{
// Use entry.Value, which is the KeyValuePair<string,int>
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…