如何检测C#中是否存在此字典密钥?

Ada*_*tle 452 c# exchangewebservices ews-managed-api

我正在使用Exchange Web服务托管API和联系人数据.我有以下代码,它是功能性的,但并不理想:

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...
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,这段代码有效.如果可能的话,现在我想减少一点.

我找不到任何允许我在尝试访问它之前检查字典中是否存在密钥的方法,如果我尝试读取它(with .ToString())并且它不存在则抛出异常:

500
字典中没有给定的密钥.

我怎样才能重构这段代码以减少(尽管仍在运行)?

Mar*_*ers 829

你可以使用ContainsKey:

if (dict.ContainsKey(key)) { ... }
Run Code Online (Sandbox Code Playgroud)

或者TryGetValue:

dict.TryGetValue(key, out value);
Run Code Online (Sandbox Code Playgroud)

更新:根据评论,这里的实际类不是IDictionarya PhysicalAddressDictionary,而是方法Contains,TryGetValue但它们以相同的方式工作.

用法示例:

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

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

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

...根据需要为每个键重复内部条件.每个PhysicalAddressKey(Home,Work等)只执行一次TryGetValue.


Joh*_*ers 11

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


小智 7

我使用字典,由于重复性和可能丢失的键,我很快修补了一个小方法:

 private static string GetKey(IReadOnlyDictionary<string, string> dictValues, string keyValue)
 {
     return dictValues.ContainsKey(keyValue) ? dictValues[keyValue] : "";
 }
Run Code Online (Sandbox Code Playgroud)

调用它:

var entry = GetKey(dictList,"KeyValue1");
Run Code Online (Sandbox Code Playgroud)

完成工作。


Dav*_*ale 5

PhysicalAddressDictionary.TryGetValue

 public bool TryGetValue (
    PhysicalAddressKey key,
    out PhysicalAddressEntry physicalAddress
     )
Run Code Online (Sandbox Code Playgroud)