我有Enumerable<KeyValuePair<TKey, TValue>>
。我想製作一個bool TryGetValue(TKey, out TValue)
擴展方法,就像它是在Dictionary<TKey, TValue>
可用。創建擴展方法TryGetValue可枚舉的(TKEY的,出TValue)<KeyValuePair <TKEY的,TValue >>就像字典的<TKEY的,TValue>中
我試圖
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;
}
這是正確的方式?如果不是,請建議一個。
注:
我不能使用字典,因爲鍵重複。而且它只會返回第一個匹配值?
What happens to the rest?
我們可以離開他們。我發送從DataTable創建的KeyValuePair。我正在查詢中使用order by columnname
創建該數據表。
我可以問你爲什麼不能使用字典中呢? –
2012-07-31 11:07:21
@ YngveB.Nilsen:因爲鍵重複。你可以有一個密鑰重複字典? – 2012-07-31 11:37:32
這就是我的想法..但不會在答案中的示例不完整呢?由於它只會返回第一個匹配值?剩下的事發生了什麼? – 2012-07-31 11:38:57