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 foreach
loop?
Example:
public static bool TryGetValue<TKey, TValue>
(this KeyValuePair<TKey, TValue>[] mapping, TKey key, out TValue value)
{
foreach(var kvp in mapping)
if (kvp.Key.Equals(key))
{
value = kvp.Value;
return true;
}
value = default(TValue);
return false;
}
Your implementation will throw an exception if the key doesn't exists due to .First()
, and FirstOrDefault()
would be ugly since KeyValuePair
is a struct and hence you can't just compare it to null
.
Sidenote:
Instead of extending KeyValuePair<TKey, TValue>[]
, you probably want to use IEnumerable<KeyValuePair<TKey, TValue>>
instead to be more flexible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.