Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if this dictionary key exists in C#?

I am working with the Exchange Web Services Managed API, with contact data. I have the following code, which is functional, but not ideal:

foreach (Contact c in contactList) {     string openItemUrl = "https://" + service.Url.Host + "/owa/" + c.WebClientReadFormQueryString;      row = table.NewRow();     row["FileAs"] = c.FileAs;     row["GivenName"] = c.GivenName;     row["Surname"] = c.Surname;     row["CompanyName"] = c.CompanyName;     row["Link"] = openItemUrl;      //home address     try { row["HomeStreet"] = c.PhysicalAddresses[PhysicalAddressKey.Home].Street.ToString(); }     catch (Exception e) { }     try { row["HomeCity"] = c.PhysicalAddresses[PhysicalAddressKey.Home].City.ToString(); }     catch (Exception e) { }     try { row["HomeState"] = c.PhysicalAddresses[PhysicalAddressKey.Home].State.ToString(); }     catch (Exception e) { }     try { row["HomeZip"] = c.PhysicalAddresses[PhysicalAddressKey.Home].PostalCode.ToString(); }     catch (Exception e) { }     try { row["HomeCountry"] = c.PhysicalAddresses[PhysicalAddressKey.Home].CountryOrRegion.ToString(); }     catch (Exception e) { }      //and so on for all kinds of other contact-related fields... } 

As I said, this code works. Now I want to make it suck a little less, if possible.

I can't find any methods that allow me to check for the existence of the key in the dictionary before attempting to access it, and if I try to read it (with .ToString()) and it doesn't exist then an exception is thrown:

500
The given key was not present in the dictionary.

How can I refactor this code to suck less (while still being functional)?

like image 563
Adam Tuttle Avatar asked May 13 '10 19:05

Adam Tuttle


People also ask

How do you check if a key is in a dictionary?

How do you check if a key exists or not in a dictionary? You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key(). 2.

How do you check if a given key already exists in a dictionary C#?

Syntax: public bool ContainsKey (TKey key); Here, the key is the Key which is to be located in the Dictionary. Return Value: This method will return true if the Dictionary contains an element with the specified key otherwise, it returns false.

What is ContainsKey C#?

ContainsKey is a Dictionary method in C# and check whether a key exists in the Dictionary or not. Declare a Dictionary and add elements − var dict = new Dictionary<string, int>() { {"TV", 1}, {"Home Theatre", 2}, {"Amazon Alexa", 3}, {"Google Home", 5}, {"Laptop", 5}, {"Bluetooth Speaker", 6} };

What does TryGetValue do?

Use the TryGetValue method if your code frequently attempts to access keys that are not in the dictionary. Using this method is more efficient than catching the KeyNotFoundException thrown by the Item[] property.


1 Answers

You can use ContainsKey:

if (dict.ContainsKey(key)) { ... } 

or TryGetValue:

dict.TryGetValue(key, out value); 

Update: according to a comment the actual class here is not an IDictionary but a PhysicalAddressDictionary, so the methods are Contains and TryGetValue but they work in the same way.

Example usage:

PhysicalAddressEntry entry; PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street; if (c.PhysicalAddresses.TryGetValue(key, out entry)) {     row["HomeStreet"] = entry; } 

Update 2: here is the working code (compiled by question asker)

PhysicalAddressEntry entry; PhysicalAddressKey key = PhysicalAddressKey.Home; if (c.PhysicalAddresses.TryGetValue(key, out entry)) {     if (entry.Street != null)     {         row["HomeStreet"] = entry.Street.ToString();     } } 

...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).

like image 106
Mark Byers Avatar answered Sep 28 '22 11:09

Mark Byers