2012-09-18 42 views
1

我有一個字典,我從數據庫中填充。如何訪問字典中唯一的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 
    // ??? 
} 
+0

爲什麼你不能遍歷字典?所以它只會迭代一次。 – Oded

+0

'First()'或'FirstOrDefault'是最明智的,但是'CandidatePlatypiDict [CandidatePlatypiDict.Keys [0]]'does not work –

回答

3

你可以根據你的需要First()Single()使用。例如:

if (CandidatePlatypiDict.Count == 1) 
{ 
    var firstPair = CandidatePlayDict.First(); 

    // can then access firstPair.Key and firstPair.Value 
    ... 
} 

有很多味道和Single()之間First(),這取決於你想要什麼。

只獲取的第一個項目,即使多個可以存在:

  • First() - 格拉布斯第一,即使許多存在,將引發沒有。
  • FirstOrDefault() - 不會拋出,如果沒有返回,則返回第一個或默認值。

爲了確保最多一個存在:

  • Single() - 確保一個且只有一個入口,拋出如果不是正好有一個。
  • SingleOrDefault() - 確保在大多數之一,如果沒有返回默認值,如果更多則返回。

所以我會選擇最能滿足您需求的。從你的問題陳述中,我推薦的是,由於似乎有空字典是一個非常普遍的結果,請首先檢查Count(如你所做的),然後致電First()

這是少得多的開銷,因爲那樣你就不必擔心異常開銷(並且Count是O(1)操作)。

3

如果您期望只有一個項目使用Single()

Dictionary<int, string> CandidatePlatypiDict = PlatypusID > 0 ? DuckbillData.GetPlatypusById(PlatypusID) : DuckbillData.GetCandidatePlatypiFromName(SearchVal); 
KeyValuePair<int, String> kvp = CandidatePlatypiDict.Single(); 
1

您可以使用Linq和使用FirstOrDefault

CandidatePlatypiDict.FirstOrDefault();