I have a Enumerable<KeyValuePair<TKey, TValue>>. I want to create a bool TryGetValue(TKey, out TValue) extension method of it just like it is available in Dictionary<TKey, TValue>.
I tried
public static bool TryGetValue<TKey, TValue>
(this Enumerable<KeyValuePair<TKey, TValue>> mapping, TKey key, out TValue value)
{
bool retVal = false;
KeyValuePair<TKey, TValue> kvp;
kvp = mapping.First(x => x.Key.Equals(key));
if(kvp.Key == null && kvp.Value == null)
{
retVal = false;
value = default(TValue);
}
else
{
retVal = true;
value = kvp.Value;
}
return retval;
}
Is this correct way? If not please suggest one.
Note:
I cannot use a Dictionary because Keys are repeated. Moreover it will only return the first matching value?
What happens to the rest?
We can leave them. I am sending KeyValuePair created from a DataTable. I am creating that DataTable using order by columnname in its query.
Why not just use a simple
foreachloop?Example:
Your implementation will throw an exception if the key doesn’t exists due to
.First(), andFirstOrDefault()would be ugly sinceKeyValuePairis a struct and hence you can’t just compare it tonull.Sidenote:
Instead of extending
KeyValuePair<TKey, TValue>[], you probably want to useIEnumerable<KeyValuePair<TKey, TValue>>instead to be more flexible.