如何检测这个字典关键字是否存在于C#中?

我正在使用Exchange Web服务托pipeAPI以及联系人数据。 我有以下代码,这是function ,但不是理想的:

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... } 

正如我所说,这个代码的作品 。 如果可能的话,现在我想让它less一些

我找不到任何方法允许我在尝试访问它之前检查字典中是否存在该键,如果我尝试读取(使用.ToString() )并且它不存在,那么exception被抛出:

500
给定的密​​钥不在字典中。

我怎样才能重构这段代码吸得less(同时仍然是function)?

你可以使用ContainsKey

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

TryGetValue

 dict.TryGetValue(key, out value); 

更新 :根据注释,这里的实际类不是一个IDictionary而是一个PhysicalAddressDictionary ,所以方法是ContainsTryGetValue但它们的工作方式相同。

用法示例:

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

更新2:这里是工作代码(由问题提问者编译)

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

…内部条件重复所需的每个关键所需。 TryGetValue每个PhysicalAddressKey(Home,Work等)只执行一次。

什么是c.PhysicalAddresses的types? 如果是Dictionary<TKey,TValue> ,那么你可以使用ContainsKey方法。

PhysicalAddressDictionary.TryGetValue

  public bool TryGetValue ( PhysicalAddressKey key, out PhysicalAddressEntry physicalAddress )