I have a Dictionary that I populate from a database.
If there is only one record returned, how can I access the KeyValuePair?
I’ve got this code:
Dictionary<int, string> CandidatePlatypiDict = PlatypusID > 0 ? DuckbillData.GetPlatypusById(PlatypusID) : DuckbillData.GetCandidatePlatypiFromName(SearchVal);
KeyValuePair<int, String> kvp;
…which populates the Dictionary just fine. When there are more than one KVPs, I display them in a DGV and then assign to kvp this way:
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);
…but if there’s only one record, I don’t need to display the values in the DGV, as there is no real choice to be made – I’ll just use that one. But so far I’m drawing a blank on how to assign the values kvp.Key and kvp.Value that I need:
if (CandidatePlatypiDict.Count == 1)
{
//kvp.Key = CandidatePlatypiDict[0]. strike 1
//kvp.Key = CandidatePlatypiDict.Keys[0] strike 2
// ???
}
You could use
First()orSingle()based on your needs. For example:There’s a lot of flavor between
Single()andFirst(), which depends on what you want.To just grab the first item even if multiple may exist:
First()– Grabs first even if many exist, throws if none.FirstOrDefault()– Won’t throw, returns first or default if none.To ensure that at most one exists:
Single()– Ensures one and only one entry, throws if not exactly one.SingleOrDefault()– Ensures at most one, returns default if none, throws if more.So I’d choose the one that best meets your needs. From your problem statement, what I’d recommend is that since it seems having an empty dictionary is a very common possible outcome, check the
Countfirst (as you are doing) and then callFirst().This is much less overhead because then you won’t have to worry about exception overhead (and
Countis a O(1) operation).