我有一個字典,我從數據庫中填充。如何訪問字典中唯一的KeyValuePair?
如果只有一條記錄返回,我如何訪問KeyValuePair?
我有這樣的代碼:
Dictionary<int, string> CandidatePlatypiDict = PlatypusID > 0 ? DuckbillData.GetPlatypusById(PlatypusID) : DuckbillData.GetCandidatePlatypiFromName(SearchVal);
KeyValuePair<int, String> kvp;
...其中填充字典就好了。當有一個以上的KVPs,我在DGV顯示出來,然後分配給KVP這樣:
DataGridViewRow selectedRow = dataGridViewPlatypi.Rows[selectedrowindex];
int i = Convert.ToInt32(selectedRow.Cells["DuckBillAccountNum"].Value);
string s = Convert.ToString(selectedRow.Cells["DuckBillName"].Value);
this.PlatypiKVP = new KeyValuePair<int, string>(i, s);
...但如果只有一個記錄,我並不需要顯示的值DGV,因爲沒有真正的選擇 - 我只會使用那個。但到目前爲止,我畫一個空白如何分配值kvp.Key和kvp.Value我需要:
if (CandidatePlatypiDict.Count == 1)
{
//kvp.Key = CandidatePlatypiDict[0]. strike 1
//kvp.Key = CandidatePlatypiDict.Keys[0] strike 2
// ???
}
爲什麼你不能遍歷字典?所以它只會迭代一次。 – Oded
'First()'或'FirstOrDefault'是最明智的,但是'CandidatePlatypiDict [CandidatePlatypiDict.Keys [0]]'does not work –